#!/usr/bin/env bash
#
# anne-clock-sync.sh
# Copyright 2026 ANNE Media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Derives ANNE network time from the local node's peer list
# (debug_getRAMvars) and compares it to the local OS clock.
#
# DRY RUN by default. Pass --apply to set the clock.
#
# uses `date` and `hwclock`.
#
# Requires: bash, curl, jq, GNU date, awk, sort, grep, mktemp
#
# ANNE epoch: 2023-12-12 23:32:00 UTC = 1702423920 unix seconds
#

set -uo pipefail

ANNE_URL="${ANNE_URL:-http://localhost:12126/anne}"
ANNE_EPOCH="${ANNE_EPOCH:-1702423920}" # 2023-12-12 23:32:00 UTC

DRIFT_TOLERANCE="${DRIFT_TOLERANCE:-5}"

MIN_PEERS="${MIN_PEERS:-4}"
ALLOWED_HEIGHT_DIFF="${ALLOWED_HEIGHT_DIFF:-1}"
MAX_SECS_SINCE_LAST_BLOCK="${MAX_SECS_SINCE_LAST_BLOCK:-3600}"

SYNC_HWCLOCK="${SYNC_HWCLOCK:-1}"
HWCLOCK_UTC="${HWCLOCK_UTC:-1}"

APPLY=0

usage() {
  cat <<EOF
Usage: $0 [--apply] [--help]

  --apply   Actually set the clock (default is dry-run only)
  --help    Show this help

Env overrides:
  ANNE_URL                     (default $ANNE_URL)
  ANNE_EPOCH                   (default $ANNE_EPOCH)
  DRIFT_TOLERANCE              (default $DRIFT_TOLERANCE)  seconds
  MIN_PEERS                    (default $MIN_PEERS)
  ALLOWED_HEIGHT_DIFF          (default $ALLOWED_HEIGHT_DIFF)
  MAX_SECS_SINCE_LAST_BLOCK    (default $MAX_SECS_SINCE_LAST_BLOCK)
  SYNC_HWCLOCK                 (default $SYNC_HWCLOCK)  0 or 1
  HWCLOCK_UTC                  (default $HWCLOCK_UTC)   0 or 1
EOF
}

for arg in "$@"; do
  case "$arg" in
    --apply)   APPLY=1 ;;
    --dry-run) APPLY=0 ;;
    --help|-h) usage; exit 0 ;;
    *) echo "unknown arg: $arg" >&2; usage; exit 2 ;;
  esac
done

need() {
  command -v "$1" >/dev/null 2>&1 || { echo "missing dependency: $1" >&2; exit 3; }
}
need curl
need jq
need date
need awk
need sort
need grep
need mktemp

if (( APPLY == 1 && SYNC_HWCLOCK == 1 )); then
  need hwclock
fi

if date -u -d "@0" >/dev/null 2>&1; then
  fmt_unix() { date -u -d "@$1" '+%Y-%m-%d %H:%M:%S UTC'; }
else
  fmt_unix() { date -u -r "$1" '+%Y-%m-%d %H:%M:%S UTC'; }
fi

TMP="$(mktemp -t anne_ramvars.XXXXXX.json)"
trap 'rm -f "$TMP"' EXIT

URL="${ANNE_URL}?requestType=debug_getRAMvars"
echo "==> Querying: $URL"

HTTP_CODE="$(curl -s -o "$TMP" -w '%{http_code}' "$URL" || true)"
if [[ "$HTTP_CODE" != "200" ]]; then
  echo "ERROR: HTTP $HTTP_CODE from ANNE node" >&2
  exit 4
fi
if ! jq -e . "$TMP" >/dev/null 2>&1; then
  echo "ERROR: response is not valid JSON" >&2
  exit 4
fi

LOCAL_HEIGHT="$(jq -r '.height // empty' "$TMP")"
if [[ -z "$LOCAL_HEIGHT" || "$LOCAL_HEIGHT" == "null" ]]; then
  echo "ERROR: no 'height' in response" >&2
  exit 4
fi

LOCAL_NODE_TIME="$(curl -s "${ANNE_URL}?requestType=getBlockchainStatus" \
  | jq -r '.time // empty' 2>/dev/null || true)"

echo "    local height        : $LOCAL_HEIGHT"
if [[ -n "$LOCAL_NODE_TIME" ]]; then
  echo "    local node ANNE time: $LOCAL_NODE_TIME"
fi
if [[ -n "${TZ:-}" ]]; then
  echo "    system TZ (env)     : $TZ"
fi
echo

# ---------------- derive per-peer estimates ----------------
PEERS_TSV="$(jq -r --argjson h "$LOCAL_HEIGHT" \
                   --argjson max "$MAX_SECS_SINCE_LAST_BLOCK" \
                   --argjson dh "$ALLOWED_HEIGHT_DIFF" '
  (.all_peers // [])[]
  | select(.green_green == true)
  | select(.last_block_timestamp != null)
  | select(.secs_since_lastblock != null)
  | select(.blockchainHeight != null)
  | select(.secs_since_lastblock <= $max)
  | select(
      (if .blockchainHeight >= $h
       then (.blockchainHeight - $h)
       else ($h - .blockchainHeight)
       end) <= $dh
    )
  | [
      (.nickname // ""),
      (.nidlongstr // ""),
      (.blockchainHeight | floor | tostring),
      (.secs_since_lastblock | floor | tostring),
      ((.last_block_timestamp + .secs_since_lastblock) | floor | tostring)
    ]
  | @tsv
' "$TMP")"

echo "==> Trusted/aligned peers used for estimation:"
if [[ -z "$PEERS_TSV" ]]; then
  echo "    (none matched the trust filters)"
  echo
  echo "ERROR: no trusted peers; cannot estimate network time." >&2
  exit 5
fi

printf '    %-20s %-22s %10s %10s %14s %14s  %s\n' \
       "NICKNAME" "NID" "HEIGHT" "SECS_AGO" "PEER_ANNE" "PEER_UNIX" "PEER_UTC"
while IFS=$'\t' read -r nick nid h secs anne; do
  [[ -z "${anne:-}" ]] && continue
  [[ "$anne" =~ ^-?[0-9]+$ ]] || continue
  punix=$(( ANNE_EPOCH + anne ))
  printf '    %-20s %-22s %10s %10s %14s %14s  %s\n' \
         "$nick" "$nid" "$h" "$secs" "$anne" "$punix" "$(fmt_unix "$punix")"
done <<< "$PEERS_TSV"
echo

PEER_COUNT="$(printf '%s\n' "$PEERS_TSV" | awk 'NF>=5 && $5 ~ /^-?[0-9]+$/ {n++} END {print n+0}')"
echo "    peers considered: $PEER_COUNT"
if (( PEER_COUNT < MIN_PEERS )); then
  echo "WARNING: fewer than MIN_PEERS=$MIN_PEERS trusted peers; result may be unreliable." >&2
fi
if (( PEER_COUNT == 0 )); then
  echo "ERROR: no usable peers." >&2
  exit 5
fi

# median over peer ANNE times
PEER_ANNE_LIST="$(printf '%s\n' "$PEERS_TSV" \
  | awk -F'\t' 'NF>=5 && $5 ~ /^-?[0-9]+$/ {print $5}' \
  | sort -n)"

MEDIAN_ANNE="$(printf '%s\n' "$PEER_ANNE_LIST" | awk '
  { a[NR]=$1 }
  END {
    if (NR==0) { print ""; exit }
    if (NR%2==1) { printf "%d\n", a[(NR+1)/2] }
    else         { printf "%d\n", int((a[NR/2] + a[NR/2+1]) / 2) }
  }')"

if [[ -z "$MEDIAN_ANNE" ]]; then
  echo "ERROR: could not compute median" >&2
  exit 5
fi

PEER_UNIX=$(( ANNE_EPOCH + MEDIAN_ANNE ))
LOCAL_UNIX="$(date +%s)"
SKEW=$(( PEER_UNIX - LOCAL_UNIX ))

echo
echo "==> Time report"
printf '    ANNE epoch (unix)      : %s\n' "$ANNE_EPOCH"
printf '    median peer ANNE time  : %s\n' "$MEDIAN_ANNE"
printf '    median peer unix time  : %s  (%s)\n' "$PEER_UNIX" "$(fmt_unix "$PEER_UNIX")"
printf '    local OS unix time     : %s  (%s)\n' "$LOCAL_UNIX" "$(fmt_unix "$LOCAL_UNIX")"
if (( SKEW >= 0 )); then
  printf '    skew (peer - local)    : +%s seconds  (local is BEHIND)\n' "$SKEW"
else
  printf '    skew (peer - local)    : %s seconds  (local is AHEAD)\n' "$SKEW"
fi
printf '    drift tolerance        : %s seconds (our policy)\n' "$DRIFT_TOLERANCE"
echo

ABS_SKEW=${SKEW#-}
if (( ABS_SKEW <= DRIFT_TOLERANCE )); then
  echo "==> Local clock is within the drift tolerance. No adjustment needed."
  exit 0
fi

echo "==> Local clock is outside the drift tolerance."
echo "    Would set OS clock to  : $(fmt_unix "$PEER_UNIX")  (unix @${PEER_UNIX})"
echo "    Adjustment amount      : ${SKEW} seconds"



if (( APPLY == 0 )); then
  echo
  echo "DRY RUN — no changes made."
  echo "Re-run with --apply, or run manually:"
  echo "    sudo date -u -s \"@${PEER_UNIX}\""
  if (( SYNC_HWCLOCK == 1 )); then
    if (( HWCLOCK_UTC == 1 )); then
      echo "    sudo hwclock --systohc --utc"
    else
      echo "    sudo hwclock --systohc --localtime"
    fi
  fi
  exit 0
fi


echo
echo "==> APPLYING: setting system clock to unix @${PEER_UNIX}"
if ! sudo date -u -s "@${PEER_UNIX}"; then
  echo "ERROR: failed to set system clock" >&2
  exit 6
fi

if (( SYNC_HWCLOCK == 1 )); then
  echo "==> Syncing hardware clock to system time..."
  if (( HWCLOCK_UTC == 1 )); then
    if ! sudo hwclock --systohc --utc; then
      echo "WARNING: failed to sync hardware clock to UTC (check /etc/adjtime)" >&2
    else
      echo "    Hardware clock updated (UTC)."
    fi
  else
    if ! sudo hwclock --systohc --localtime; then
      echo "WARNING: failed to sync hardware clock to localtime (check /etc/adjtime)" >&2
    else
      echo "    Hardware clock updated (localtime)."
    fi
  fi
fi

NEW_UNIX="$(date +%s)"
printf '    new local unix time    : %s  (%s)\n' "$NEW_UNIX" "$(fmt_unix "$NEW_UNIX")"
printf '    residual skew          : %s seconds\n' "$(( PEER_UNIX - NEW_UNIX ))"
echo "==> Done."
