#!/usr/bin/env bash
# install-ccusage-sync.sh - Install multi-device AI coding usage synchronization.

set -euo pipefail
IFS=$'\n\t'

readonly SCRIPT_NAME="${0##*/}"
readonly INSTALLER_URL_DEFAULT='https://opengist.resetrix.work/weehong/ai-coding-agent/raw/HEAD/sync-ccusage.sh'
readonly INSTALL_PATH="$HOME/.local/bin/sync-ccusage"
readonly CRON_ENTRY='*/5 * * * * "$HOME/.local/bin/sync-ccusage" >/dev/null 2>&1'
INSTALLER_URL="${CCUSAGE_INSTALLER_URL:-$INSTALLER_URL_DEFAULT}"
DRY_RUN=0

usage() {
  cat <<EOF
Usage: $SCRIPT_NAME [--dry-run] [--help]

Downloads and validates the public CCUsage sync installer, then installs:

  $INSTALL_PATH

The installed script synchronizes Claude Code, Codex CLI, and OpenCode data
with a preconfigured Hetzner Storage Box every five minutes.

Prerequisite:
  The SSH alias hetzner-ccusage-storage-box and its authorized identity key
  must already be configured for this user.

Options:
  --dry-run    Download and validate the installer without executing it.
  --help, -h   Show this help.

Environment:
  CCUSAGE_INSTALLER_URL  Override the canonical installer URL.
EOF
}

log()  { printf '\033[1;34m[%s]\033[0m %s\n' "${SCRIPT_NAME%.sh}" "$*"; }
die()  { printf '\033[1;31m[%s] ERROR:\033[0m %s\n' "${SCRIPT_NAME%.sh}" "$*" >&2; exit 1; }

trap 'rc=$?; (( rc )) && printf "\033[1;31m[%s] failed at line %s (exit %d)\033[0m\n" "${SCRIPT_NAME%.sh}" "$LINENO" "$rc" >&2' ERR

while (( $# )); do
  case "$1" in
    --dry-run) DRY_RUN=1 ;;
    -h|--help) usage; exit 0 ;;
    *) die "Unknown argument: $1 (try --help)" ;;
  esac
  shift
done

(( EUID != 0 )) || die "Do not run as root. Run as your normal user."

for tool in bash curl grep head mktemp; do
  command -v "$tool" >/dev/null 2>&1 || die "Missing required tool: $tool"
done

if [[ -r /etc/os-release ]]; then
  # shellcheck disable=SC1091
  . /etc/os-release
  case "${ID:-}:${ID_LIKE:-}" in
    *ubuntu*|*debian*) : ;;
    *) die "Unsupported distro: ${PRETTY_NAME:-unknown}." ;;
  esac
else
  die "/etc/os-release not found."
fi

STAGE="$(mktemp -d -t ccusage-sync.XXXXXX)"
trap 'rm -rf "$STAGE"' EXIT
DOWNLOADED_INSTALLER="$STAGE/sync-ccusage.sh"

log "Downloading canonical installer..."
curl --proto '=https' --tlsv1.2 -fsSL --max-time 60 --retry 2 \
  "$INSTALLER_URL" -o "$DOWNLOADED_INSTALLER"

[[ -s "$DOWNLOADED_INSTALLER" ]] || die "Downloaded installer is empty."
head -n1 "$DOWNLOADED_INSTALLER" | grep -qE '^#!/usr/bin/env bash$' \
  || die "Downloaded installer has an unexpected shebang."
bash -n "$DOWNLOADED_INSTALLER" \
  || die "Downloaded installer failed Bash syntax validation."
grep -qF 'hetzner-ccusage-storage-box' "$DOWNLOADED_INSTALLER" \
  || die "Downloaded installer does not contain the expected SSH target."

if (( DRY_RUN )); then
  log "Validated installer: $INSTALLER_URL"
  log "Would run the installer as the current user."
  log "Would install: $INSTALL_PATH"
  log "Would install cron: $CRON_ENTRY"
  exit 0
fi

log "Running the CCUsage installer..."
bash "$DOWNLOADED_INSTALLER" install

[[ -x "$INSTALL_PATH" ]] \
  || die "Installed script is missing or not executable: $INSTALL_PATH"
bash -n "$INSTALL_PATH" \
  || die "Installed script failed Bash syntax validation."
crontab -l 2>/dev/null | grep -Fqx "$CRON_ENTRY" \
  || die "The five-minute CCUsage cron entry was not installed."

log "CCUsage sync installation verified."
log "Synced logs are available under: $HOME/.ccusage-synced-logs"
log "Cron schedule: $CRON_ENTRY"
