#!/bin/sh
set -eu

[ "$#" -eq 1 ] || { echo 'usage: gic-local-pool status|drain|undrain|enable-distributed-lock' >&2; exit 2; }
ACTION=$1
ENV=/etc/gic/gic.env
DRAIN=/var/lib/gic/drain

case "$ACTION" in
  status)
    if systemctl is-active --quiet gic-workers.service; then echo active; else echo inactive; fi
    [ -e "$DRAIN" ] && echo draining || echo accepting
    if grep -q '^GIC_DISTRIBUTED_LOCK=1$' "$ENV" 2>/dev/null; then echo distributed-lock=enabled; else echo distributed-lock=disabled; fi
    exit 0
    ;;
  drain)
    install -d -m 0755 -o gic -g gic /var/lib/gic
    : > "$DRAIN"
    chown gic:gic "$DRAIN"
    echo DRAINING
    exit 0
    ;;
  undrain)
    rm -f "$DRAIN"
    echo ACTIVE
    exit 0
    ;;
  enable-distributed-lock)
    tmp=$(mktemp)
    trap 'rm -f "$tmp"' EXIT
    awk '
      BEGIN{done=0}
      /^GIC_DISTRIBUTED_LOCK=/{if(!done){print "GIC_DISTRIBUTED_LOCK=1";done=1}next}
      {print}
      END{if(!done)print "GIC_DISTRIBUTED_LOCK=1"}
    ' "$ENV" > "$tmp"
    install -m 0600 -o root -g root "$tmp" "$ENV"
    echo DISTRIBUTED_LOCK_ENABLED
    exit 0
    ;;
  *)
    echo 'invalid action' >&2
    exit 2
    ;;
esac
