#!/bin/bash
# Upgrade DevDesk from the LotusGuild apt registry. Run by the host's webhook
# listener (hook "devdesk-deploy") when CI publishes a v* tag; the tag's ref is
# passed as $1. Safe for running sessions: package upgrades restart only
# devdesk.service (ttyd), never devdesk-tmux.service where Claude lives.
set -euo pipefail

LOG=${DEVDESK_DEPLOY_LOG:-/var/log/devdesk-deploy.log}
SOURCES=${DEVDESK_APT_SOURCES:-sources.list.d/lotusguild.list}

log() {
    printf '%s %s\n' "$(date '+%F %T')" "$*" >>"$LOG"
}

exec 9>/run/devdesk-deploy.lock
flock -w 900 9 || {
    log "another deploy is still running; giving up"
    exit 1
}

want=${1:-}
want=${want#refs/tags/}
want=${want#v}
before=$(dpkg-query -W -f='${Version}' devdesk 2>/dev/null || echo none)
log "=== deploy: installed $before, release ${want:-latest}"

refresh() {
    apt-get update -q -o Dir::Etc::sourcelist="$SOURCES" -o Dir::Etc::sourceparts=- \
        -o APT::Get::List-Cleanup=0 >>"$LOG" 2>&1
}

# The registry can lag the release by a few seconds: wait for the tagged version.
candidate=""
for _ in $(seq 1 18); do
    refresh || true
    candidate=$(apt-cache policy devdesk | awk '/Candidate:/ {print $2}')
    if [ -z "$want" ] || [ "$candidate" = "$want" ]; then
        break
    fi
    sleep 10
done

if [ -n "$want" ] && [ "$candidate" != "$want" ]; then
    log "registry still offers $candidate, not $want; giving up"
    exit 1
fi
if [ "$candidate" = "$before" ]; then
    log "already at $before; nothing to do"
    exit 0
fi

DEBIAN_FRONTEND=noninteractive apt-get install -y -q --only-upgrade \
    -o Dpkg::Options::=--force-confold devdesk </dev/null >>"$LOG" 2>&1
log "devdesk $before -> $(dpkg-query -W -f='${Version}' devdesk)"
