#!/usr/bin/env bash
# deploy-status — say what the local deploy is doing right now, in plain language.
# Reads only: the state file deploy-local.sh publishes, and the deploy queue directory.
# --json prints the raw state record instead.
set -uo pipefail

STATE="${OVERDECK_DEPLOY_STATE_FILE:-${XDG_STATE_HOME:-$HOME/.local/state}/overdeck/deploy-status.json}"
DEPLOY="${OVERDECK_DEPLOY_DIR:-$HOME/.local/share/overdeck/deploy}"
QUEUE="${OVERDECK_DEPLOY_QUEUE_DIR:-${DEPLOY}-queue}"

if [[ "${1:-}" == "--json" ]]; then
  [[ -r "$STATE" ]] || { echo '{"schema":1,"state":"unknown"}'; exit 0; }
  cat "$STATE"
  exit 0
fi

field() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" <<<"$record"; }
number() { sed -n "s/.*\"$1\":\([0-9]*\).*/\1/p" <<<"$record"; }

human_age() {
  local s=$1
  (( s < 90 )) && { printf '%ds' "$s"; return; }
  (( s < 5400 )) && { printf '%dm' "$((s / 60))"; return; }
  printf '%dh%dm' "$((s / 3600))" "$(((s % 3600) / 60))"
}

shopt -s nullglob
queued=("$QUEUE"/req-*)
shopt -u nullglob

if [[ ! -r "$STATE" ]]; then
  echo "No deploy has reported status yet on this machine."
  echo "Waiting to deploy: ${#queued[@]}"
  exit 0
fi

record=$(cat "$STATE")
state=$(field state)
step=$(field step)
detail=$(field detail)
sha=$(field sha)
pid=$(number pid)
started=$(number started_at)
updated=$(number updated_at)
now=$(date +%s)

alive=no
[[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null && alive=yes

case "$state" in
  running)
    if [[ "$alive" == yes ]]; then
      echo "Deploying now: ${detail:-$step}"
      echo "Running for $(human_age $((now - started))), last progress $(human_age $((now - updated))) ago."
    else
      echo "A deploy stopped without finishing while it was: ${detail:-$step}"
      echo "It last reported $(human_age $((now - updated))) ago and is no longer running."
    fi
    ;;
  finished)
    echo "Idle. Last deploy finished successfully $(human_age $((now - updated))) ago: ${detail:-$step}"
    ;;
  failed)
    echo "Last deploy FAILED $(human_age $((now - updated))) ago while: ${step}"
    [[ -n "$detail" ]] && echo "Reason: $detail"
    ;;
  *)
    echo "Deploy status is unreadable — the status file does not say what is happening."
    exit 1
    ;;
esac

[[ -n "$sha" ]] && echo "Code version: $sha"
echo "Waiting to deploy: ${#queued[@]}"
