#!/bin/bash
set -euo pipefail

if (( $# != 2 )) || [[ $1 != prepare && $1 != apply && $1 != start && $1 != service ]]; then
    echo 'Usage: moonbot-update start|prepare|apply|service INSTANCE_DIRECTORY' >&2
    exit 1
fi
cd -- "$2"
directory=$PWD
ready=$directory/updates/ready
previous=$directory/updates/previous
mode=$1
stage=PREPARE
log() { printf '[updater] %s instance=%s\n' "$*" "$directory"; }
trap 'status=$?; if (( status )); then log "${stage}_FAILED status=$status" >&2; fi' EXIT

# /proc/uptime is monotonic even if the wall clock is corrected during shutdown.
now() { read -r uptime _ </proc/uptime; echo "${uptime%.*}"; }

if [[ $mode == start || $mode == service ]]; then
    unit=$(systemd-escape --path --template=moonbot@.service "$directory")
    update_unit=${unit/moonbot@/moonbot-update@}
fi
if [[ $mode == start ]]; then
    # Refuse a console core: stopping a different service would not stop our caller.
    [[ $(systemctl show --value -p MainPID "$unit") == "$PPID" ]] || {
        log "Run MoonBot as $unit to update it" >&2; exit 1;
    }
fi

verify() (
    cd -- "$1"
    sha256sum --quiet --strict --check SHA256SUMS
    diff -u <(find . -type f ! -path ./SHA256SUMS ! -path ./manifest.json -printf '%P\n' | LC_ALL=C sort) \
        <(cut -c67- SHA256SUMS | LC_ALL=C sort)
    /lib64/ld-linux-x86-64.so.2 --verify ./MoonBot
)

if [[ $mode == prepare || $mode == start ]]; then
    version=$(<updates/BOTversion.txt)
    version=${version%$'\r'}
    [[ $version =~ ^ADCNewVer=([0-9]+)$ ]] || { echo 'Invalid BOTversion.txt' >&2; exit 1; }
    archive=$directory/updates/ver-${BASH_REMATCH[1]}.zip
    log "PREPARE version=$version archive=$archive"
    rm -rf -- "$ready"
    mkdir -- "$ready"
    trap 'status=$?; if (( status )); then log "${stage}_FAILED status=$status" >&2; rm -rf -- "$ready"; fi' EXIT
    unzip -Z1 "$archive" | while IFS= read -r name; do
        case "$name" in
            /*|*\\*|../*|*/../*|*/..) echo "Invalid ZIP path: $name" >&2; exit 1 ;;
        esac
    done
    unzip -q "$archive" -d "$ready"
    verify "$ready"
    log PREPARE_OK
    if [[ $mode == start ]]; then
        # Existing installations may use a per-instance unit. Preserve their other settings.
        dropin=/etc/systemd/system/$unit.d
        mkdir -p -- "$dropin"
        cat >"$dropin/update.conf" <<'UNIT'
[Service]
Type=exec
KillMode=mixed
TimeoutStopSec=120
SendSIGKILL=yes
FinalKillSignal=SIGKILL
StandardOutput=journal
StandardError=journal
UNIT
        if [[ ! -f $dropin/update-exit.conf ]] &&
            [[ $(systemctl show --value -p ExecStopPost "$unit") != *MOONBOT_EXIT* ]]; then
            cat >"$dropin/update-exit.conf" <<'UNIT'
[Service]
ExecStopPost=/bin/sh -c 'echo "MOONBOT_EXIT result=$$SERVICE_RESULT code=$$EXIT_CODE status=$$EXIT_STATUS"'
UNIT
        fi
        systemctl daemon-reload
        # With journald's default Storage=auto this enables persistent storage.
        mkdir -p /var/log/journal
        systemd-tmpfiles --create --prefix /var/log/journal
        journalctl --flush
        stage=UPDATER_START
        systemd-run --quiet --collect --expand-environment=no --unit="$update_unit" --property=Type=exec --property=Restart=no \
            --property=UMask=0077 --property=StandardOutput=journal --property=StandardError=journal \
            /bin/bash "$(realpath -- "$0")" service "$directory"
        log "UPDATER_STARTED unit=$update_unit"
    fi
    exit 0
fi

if [[ $mode == service ]]; then
    stage=STOP
    cgroup=$(systemctl show --value -p ControlGroup "$unit")
    [[ $cgroup == /* && $cgroup != / ]] || { log 'Cannot identify the old service cgroup' >&2; exit 1; }
    group=/sys/fs/cgroup$cgroup
    [[ -r $group/cgroup.events ]] || { log 'A unified cgroup v2 hierarchy is required' >&2; exit 1; }

    log STOP_REQUESTED
    systemctl stop --no-block "$unit"
    kill_at=$(( $(now) + 120 ))
    deadline=$((kill_at + 300))
    delay=1
    killed=false
    while [[ -d $group ]]; do
        if events=$(cat "$group/cgroup.events"); then
            if grep -qx 'populated 0' <<<"$events"; then break; fi
        else
            log STOP_CHECK_FAILED >&2
        fi
        current=$(now)
        if (( current >= kill_at )) && ! $killed; then
            # systemd sends the final SIGKILL; a stop timeout is not an installation failure.
            log 'STOP_KILL_WAIT timeout=300'
            killed=true
            delay=1
        fi
        if (( current >= deadline )); then
            log 'STOP_STUCK timeout=300; leaving installed files unchanged' >&2
            while IFS= read -r path; do
                while IFS= read -r pid; do ps -p "$pid" -o pid=,ppid=,stat=,wchan=,comm= >&2 || true; done <"$path"
            done < <(find "$group" -name cgroup.procs)
            exit 1
        fi
        until=$deadline
        if ! $killed; then until=$kill_at; fi
        remaining=$((until - current))
        if (( delay > remaining )); then delay=$remaining; fi
        sleep "$delay"
        case $delay in 1) delay=2 ;; 2) delay=5 ;; *) delay=10 ;; esac
    done
    log STOPPED
else
    # Legacy cores exec apply after shutdown. Do not inherit their sockets/locks into the new core.
    for path in /proc/$$/fd/*; do
        fd=${path##*/}
        if (( fd > 2 && fd != 255 )); then exec {fd}>&-; fi
    done
fi

replaced=()
rollback() {
    trap - EXIT
    set -e
    echo 'MoonBot update failed, restarting the previous executable.' >&2
    for (( i=${#replaced[@]}-1; i>=0; i-- )); do
        name=${replaced[i]}
        rm -rf -- "$directory/$name"
        if [[ -e $previous/$name || -L $previous/$name ]]; then
            mv -- "$previous/$name" "$directory/$name"
        fi
    done
    exec "$directory/MoonBot"
}
if [[ $mode == apply ]]; then
    trap rollback EXIT
    verify "$ready"
fi
stage=INSTALL
log INSTALL
rm -rf -- "$previous"
mkdir -- "$previous"
shopt -s nullglob dotglob execfail
for path in "$ready"/*; do
    name=${path##*/}
    if [[ -e $directory/$name || -L $directory/$name ]]; then
        mv -- "$directory/$name" "$previous/$name"
    fi
    replaced+=("$name")
    mv -- "$path" "$directory/$name"
done
if [[ -f mb ]]; then
    if [[ ! -e /usr/local/bin/mb || mb -nt /usr/local/bin/mb ]]; then
        install -p -m 755 mb /usr/local/bin/mb
    fi
    ln -sfn mb /usr/local/bin/moonbot
fi
rm -f updates/BOTversion.txt
rmdir -- "$ready"
log INSTALL_OK
if [[ $mode == service ]]; then
    stage=START
    log START_REQUESTED
    systemctl start "$unit"
    log START_EXECUTED
    exit 0
fi
# Bash's errexit bypasses execfail; let a failed exec reach the EXIT rollback.
set +e
exec "$directory/MoonBot"
