#!/bin/sh
set -eu
export DEBIAN_FRONTEND=noninteractive
[ "$#" -eq 1 ] || { echo 'usage: gic-worker-deploy VERSION' >&2; exit 2; }
case "$1" in *[!0-9.]*|'') echo 'invalid version' >&2; exit 2;; esac
TARGET=$1
CURRENT=$(dpkg-query -W -f='${Version}' gic 2>/dev/null || true)
CURRENT_STATUS=$(dpkg-query -W -f='${Status}' gic 2>/dev/null || true)
[ -n "$CURRENT" ] || { echo 'gic is not installed' >&2; exit 3; }
if [ "$TARGET" = "$CURRENT" ] && [ "$CURRENT_STATUS" = "install ok installed" ]; then
  echo "already $CURRENT"
  exit 0
fi
apt-get update -qq
apt-cache madison gic | awk '{print $3}' | grep -Fx "$TARGET" >/dev/null || { echo "gic $TARGET not found in configured APT repositories" >&2; exit 4; }
health() {
  systemctl is-active --quiet gic-workers.service || return 1
  i=0
  while [ "$i" -lt 20 ]; do
    n=$(pgrep -u gic -f '/usr/lib/gic/runtime/node worker/index.js' 2>/dev/null | wc -l)
    [ "$n" -eq 10 ] && grep -h 'Subscribed to RabbitMQ queue=tasks prefetch=1' /var/log/gic/worker-*.log 2>/dev/null | tail -10 | [ "$(wc -l)" -eq 10 ] && return 0
    sleep 1; i=$((i+1))
  done
  return 1
}
echo "deploy $CURRENT -> $TARGET"
apt-get install -y -qq --allow-downgrades -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold "gic=$TARGET"
systemctl restart gic-workers.service
if health; then echo "DEPLOY_OK version=$TARGET"; exit 0; fi
echo "healthcheck failed; rollback -> $CURRENT" >&2
apt-get install -y -qq --allow-downgrades -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold "gic=$CURRENT" || { echo 'ROLLBACK_INSTALL_FAILED' >&2; exit 20; }
systemctl restart gic-workers.service
if health; then echo "ROLLBACK_OK version=$CURRENT" >&2; exit 10; fi
echo 'ROLLBACK_HEALTH_FAILED' >&2; exit 21
