#!/usr/bin/env bash
# now-phoenix.sh — emit the current America/Phoenix timestamp, deterministically.
#
# WHY: `TZ=America/Phoenix date` is unreliable on Git-for-Windows bash (the MSYS
# tz database is often absent, so it silently returns UTC). Arizona does NOT
# observe DST — it is fixed UTC-7 (MST) year-round — so we compute Phoenix time
# as (UTC epoch - 7h) and format it. No tz database, no DST edge cases, identical
# result on Windows / macOS / Linux.
#
# Usage:
#   bash now-phoenix.sh             -> 2026-06-08 14:32 PT   (default, human log line)
#   bash now-phoenix.sh --iso       -> 2026-06-08T14:32:07-07:00
#   bash now-phoenix.sh --date      -> 2026-06-08
#   bash now-phoenix.sh --datetime  -> 2026-06-08 14:32:07
#   bash now-phoenix.sh --epoch     -> 1749422327   (raw UTC epoch, for arithmetic)
#   bash now-phoenix.sh --fmt '+%H:%M'  -> 14:32   (custom strftime, applied to Phoenix time)
#
# All output is on stdout, no trailing prose. Soft, dependency-free (coreutils date only).

set -euo pipefail

OFFSET=$((7 * 3600))            # Phoenix is UTC-7, fixed
EPOCH_UTC="$(date -u +%s)"
EPOCH_PHX=$((EPOCH_UTC - OFFSET))

# Portable "format an epoch as if it were UTC" (so the wall-clock we print is Phoenix local).
fmt_epoch() {
    local e="$1" f="$2"
    if date -u -d "@${e}" "$f" >/dev/null 2>&1; then
        date -u -d "@${e}" "$f"        # GNU/Git-Bash
    else
        date -u -r "${e}" "$f"         # BSD/macOS
    fi
}

case "${1:-}" in
    --iso)       printf '%s-07:00\n' "$(fmt_epoch "$EPOCH_PHX" '+%Y-%m-%dT%H:%M:%S')" ;;
    --date)      fmt_epoch "$EPOCH_PHX" '+%Y-%m-%d' ;;
    --datetime)  fmt_epoch "$EPOCH_PHX" '+%Y-%m-%d %H:%M:%S' ;;
    --epoch)     printf '%s\n' "$EPOCH_UTC" ;;
    --fmt)       fmt_epoch "$EPOCH_PHX" "${2:?--fmt needs a strftime arg, e.g. --fmt '+%H:%M'}" ;;
    ''|--pt)     printf '%s PT\n' "$(fmt_epoch "$EPOCH_PHX" '+%Y-%m-%d %H:%M')" ;;
    -h|--help)
        grep -E '^#( |$)' "$0" | sed 's/^# \{0,1\}//'
        ;;
    *)
        echo "[ERROR] now-phoenix: unknown arg '$1' (try --help)" >&2
        exit 64
        ;;
esac
