#!/bin/sh
# veyra-helper -- runs apt for Veyra, as root.
#
# Veyra runs inside AppleTV.app, which cannot run apt itself (apt needs root,
# and a package's postinst may restart AppleTV.app mid-install).  So Veyra
# drops a one-line request into $QUEUE and launchd (QueueDirectories in
# io.github.mattkje.veyra.helper.plist) starts this script as root.  It works
# through the queue, oldest first, and exits.  Progress goes to $STATUS and
# $LOG, which Veyra polls.
#
# Requests (one per file):
#   update                 apt-get update
#   install PACKAGE        apt-get install PACKAGE
#   remove PACKAGE         apt-get remove PACKAGE
#   add-source URL         add "deb URL ./" to $SOURCES, then update
#   remove-source URL      drop it from $SOURCES, then update
#
# Any local process can write to the queue, so every argument is checked
# against a strict character set and passed to apt quoted.  Only $SOURCES is
# ever edited.

DIR=/var/mobile/Library/Veyra
QUEUE=$DIR/queue
STATUS=$DIR/status
LOG=$DIR/log.txt
SOURCES=/etc/apt/sources.list.d/veyra.list

export PATH=/usr/bin:/bin:/usr/sbin:/sbin HOME=/var/root DEBIAN_FRONTEND=noninteractive
# Our packages' postinst skip restarting AppleTV.app when they see this; Veyra
# offers the restart once the task is done.
export VEYRA=1

status() {
    printf '%s\n' "$1" > "$STATUS.tmp" && chmod 644 "$STATUS.tmp" && mv -f "$STATUS.tmp" "$STATUS"
}

apt() {
    echo "\$ apt-get $*" >> "$LOG"
    apt-get "$@" < /dev/null >> "$LOG" 2>&1
}

valid_package() {
    case $1 in
        ''|?|*[!a-z0-9+.-]*|[!a-z0-9]*) return 1 ;;
    esac
    [ ${#1} -le 128 ]
}

valid_url() {
    case $1 in
        http://?*|https://?*) ;;
        *) return 1 ;;
    esac
    case $1 in
        *[!A-Za-z0-9._~:/%-]*) return 1 ;;
    esac
    [ ${#1} -le 300 ]
}

# Rewrites $SOURCES with "deb $1 ./" added (add) or removed (remove).
edit_sources() {
    line="deb $1 ./"
    touch "$SOURCES"
    grep -vxF "$line" "$SOURCES" | grep -v '^$' > "$SOURCES.tmp"
    [ "$2" = add ] && echo "$line" >> "$SOURCES.tmp"
    chmod 644 "$SOURCES.tmp" && mv -f "$SOURCES.tmp" "$SOURCES"
}

# Packages the main menu itself needs: without them no appliance loads, Veyra
# included, and only SSH could bring them back.  (Veyra hides their Remove
# button too; this is the check that counts.)
PROTECTED="beigelist mobilesubstrate com.saurik.substrate.safemode com.saurik.afc2d \
io.github.mattkje.veyra apt7 apt7-lib dpkg"

remove() {
    for p in $PROTECTED; do
        if [ "$p" = "$1" ]; then
            echo "veyra-helper: $1 is needed by the main menu and is not removed here" >> "$LOG"
            return 3
        fi
    done
    # apt -y would also remove everything that depends on it: only go ahead
    # when the simulation removes this one package.
    others=$(apt-get -s remove "$1" 2>/dev/null | sed -n 's/^Remv \([^ ]*\).*/\1/p' | grep -vxF "$1")
    if [ -n "$others" ]; then
        echo "veyra-helper: removing $1 would also remove: $(echo $others)" >> "$LOG"
        return 4
    fi
    apt -y --force-yes remove "$1"
}

handle() {
    op=$1 arg=$2 extra=$3
    rm -f "$LOG"
    status "running $op${arg:+ $arg}"
    code=2
    if [ -n "$extra" ]; then
        echo "veyra-helper: refused request (too many words)" >> "$LOG"
    elif [ "$op" = update ] && [ -z "$arg" ]; then
        apt update; code=$?
    elif [ "$op" = install ] && valid_package "$arg"; then
        apt -y --force-yes install "$arg"; code=$?
    elif [ "$op" = remove ] && valid_package "$arg"; then
        remove "$arg"; code=$?
    elif { [ "$op" = add-source ] || [ "$op" = remove-source ]; } && valid_url "$arg"; then
        case $arg in */) ;; *) arg=$arg/ ;; esac      # apt wants the trailing slash
        if edit_sources "$arg" "${op%-source}"; then apt update; code=$?; else code=1; fi
    else
        echo "veyra-helper: refused request" >> "$LOG"
    fi
    status "done $code $op${arg:+ $arg}"
}

while :; do
    next=$(ls "$QUEUE" 2>/dev/null | head -n 1)     # names are timestamps: oldest first
    [ -n "$next" ] || exit 0
    req=$(head -n 1 "$QUEUE/$next")
    rm -f "$QUEUE/$next"
    set -f                                          # no globbing of the request's words
    # shellcheck disable=SC2086
    [ -n "$req" ] && handle $req
    set +f
done
