#!/bin/zsh
# Monthly fetch of HMWSSB data from Open Data Telangana, run by launchd on Teja's Mac
# (label in.urbanobservatory.hmwssb-fetch, last day of each month 09:00 IST). The portal only answers
# from Indian connections, so this cannot run on GitHub Actions or Cloudflare.
#
# Pulls main, runs fetch.py, commits and pushes as hulf-observatory when a data file is
# new or changed. The push credential is read from gh's keyring at run time
# (`gh auth token -u hulf-observatory`); nothing is stored here and gh's active account
# is not switched. Log: ~/Library/Logs/hmwssb-fetch.log
set -euo pipefail
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
REPO="${HMWSSB_REPO:-$HOME/hulf-observatory/hmwssb-data}"
cd "$REPO"
# launchd fires this on the 28th-31st; only the last day of the month goes ahead.
# HMWSSB_FORCE=1 skips the check (manual runs).
if [[ "${HMWSSB_FORCE:-}" != "1" && "$(date -v+1d +%d)" != "01" ]]; then
  echo "== $(date '+%Y-%m-%d %H:%M:%S') not the last day of the month, skipping"; exit 0
fi
echo "== $(date '+%Y-%m-%d %H:%M:%S') start"

helper='!f(){ echo username=hulf-observatory; echo "password=$(gh auth token -u hulf-observatory)"; }; f'

if [[ -n "$(git status --porcelain)" ]]; then
  echo "working tree not clean, refusing to run"; git status --short; exit 1
fi
git -c credential.helper= -c credential.helper="$helper" pull --ff-only --quiet origin main

python3 fetch.py

if git status --porcelain | grep -vE 'manifest\.json$' | grep -q .; then
  git add -A
  git -c user.name=hulf-observatory -c user.email=218873788+hulf-observatory@users.noreply.github.com \
      commit --quiet -m "Fetch from Open Data Telangana $(date +%Y-%m-%d)"
  git -c credential.helper= -c credential.helper="$helper" push --quiet origin main
  echo "pushed $(git rev-parse --short HEAD)"
else
  git checkout --quiet -- . 2>/dev/null || true   # drop the manifest timestamp churn
  echo "no new data"
fi
echo "== $(date '+%Y-%m-%d %H:%M:%S') done"
