#!/bin/sh
set -eu
[ "$#" -eq 2 ] || { echo 'usage: gic-regional-pool start|stop|restart|status|drain|undrain|scan-other REGION' >&2; exit 2; }
ACTION=$1
REGION=$2
case "$ACTION" in start|stop|restart|status|drain|undrain|scan-other) ;; *) echo 'invalid action' >&2; exit 2;; esac
case "$REGION" in
  ''|*[!A-Za-z0-9._-]*) echo 'invalid region' >&2; exit 2;;
esac
UNIT="gic-workers@$REGION.service"
DRAIN="/var/lib/gic/drain-$REGION"
case "$ACTION" in
  scan-other)
    case "$REGION" in local) REALM=2;; *) echo "scan-other currently supports region local only" >&2; exit 2;; esac
    exec /usr/sbin/runuser -u gic -- /usr/lib/gic/runtime/node /usr/lib/gic/scripts/scan-other-subtypes.js "$REALM"
    ;;
  drain) install -d -m 0755 /var/lib/gic; : > "$DRAIN"; echo "DRAINING $REGION"; exit 0;;
  undrain) rm -f "$DRAIN"; echo "ACTIVE $REGION"; exit 0;;
  status)
    if systemctl is-active --quiet "$UNIT"; then echo active; else echo inactive; fi
    [ -e "$DRAIN" ] && echo draining || echo accepting
    exit 0;;
  stop)
    systemctl stop "$UNIT"
    if systemctl is-active --quiet "$UNIT"; then echo "failed to stop $UNIT" >&2; exit 1; fi
    echo inactive
    exit 0;;
esac
systemctl "$ACTION" "$UNIT"
systemctl is-active "$UNIT"
