#!/usr/bin/env bash
set -euo pipefail
STATE=/run/mx240a/registration-open-until
usage(){ echo "Usage: mx240a-cli-control registration {open [seconds]|close|status}"; exit 2; }
[[ $# -ge 2 && "$1" == registration ]] || usage
case "$2" in
 open)
  secs="${3:-60}"
  [[ "$secs" =~ ^[0-9]+$ ]] && ((secs>=1 && secs<=3600)) || { echo "Seconds must be 1..3600"; exit 2; }
  install -d -m755 /run/mx240a
  echo $(( $(date +%s)+secs )) > "$STATE"
  chmod 644 "$STATE"
  echo "MX240a registration OPEN for $secs seconds."
  ;;
 close) rm -f "$STATE"; echo "MX240a registration CLOSED." ;;
 status)
  now=$(date +%s); until=0; [[ -f "$STATE" ]] && until=$(cat "$STATE" 2>/dev/null || echo 0)
  if [[ "$until" =~ ^[0-9]+$ ]] && ((until>now)); then echo "MX240a registration OPEN ($((until-now)) seconds remaining)."
  else rm -f "$STATE" 2>/dev/null || true; echo "MX240a registration CLOSED."; fi ;;
 *) usage ;;
esac
