#!/usr/bin/env bash
set -euo pipefail

HOST=""
REMOTE_ROOT="/opt/lingniu-go-native"
ON_CALENDAR="*-*-* *:*:00"
TIMEOUT="2m"
APPLY="true"
PRUNE_UNMANAGED="false"
PRUNE_MIN_AGE="1h"
RETIRE_STALE_UNMANAGED="false"
RETIRE_MIN_AGE="8h"

usage() {
  cat <<'USAGE'
Usage:
  scripts/install-identity-source-sync-timer.sh --host root@115.29.187.205 [options]

Options:
  --host HOST          SSH target for ECS installation.
  --remote-root DIR   Remote install root. Defaults to /opt/lingniu-go-native.
  --on-calendar SPEC  systemd OnCalendar value. Defaults to "*-*-* *:*:00".
  --timeout DURATION  identity-import timeout. Defaults to 2m.
  --dry-run           Install timer without -apply.
  --prune-unmanaged   Also prune stale unmanaged vehicle_data_source rows.
  --prune-min-age DUR Minimum age for --prune-unmanaged. Defaults to 1h.
  --retire-stale-unmanaged
                       Disable stale unmanaged vehicle_data_source rows that may be referenced by historical mileage.
  --retire-min-age DUR
                       Minimum age for --retire-stale-unmanaged. Defaults to 8h.
  -h, --help          Show this help.
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --host)
      HOST="${2:-}"
      shift 2
      ;;
    --remote-root)
      REMOTE_ROOT="${2:-}"
      shift 2
      ;;
    --on-calendar)
      ON_CALENDAR="${2:-}"
      shift 2
      ;;
    --timeout)
      TIMEOUT="${2:-}"
      shift 2
      ;;
    --dry-run)
      APPLY="false"
      shift
      ;;
    --prune-unmanaged)
      PRUNE_UNMANAGED="true"
      shift
      ;;
    --prune-min-age)
      PRUNE_MIN_AGE="${2:-}"
      shift 2
      ;;
    --retire-stale-unmanaged)
      RETIRE_STALE_UNMANAGED="true"
      shift
      ;;
    --retire-min-age)
      RETIRE_MIN_AGE="${2:-}"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [[ -z "$HOST" ]]; then
  echo "--host is required" >&2
  usage >&2
  exit 2
fi

if [[ -z "$ON_CALENDAR" ]]; then
  echo "--on-calendar must not be empty" >&2
  exit 2
fi
if [[ -z "$TIMEOUT" ]]; then
  echo "--timeout must not be empty" >&2
  exit 2
fi
if [[ -z "$PRUNE_MIN_AGE" ]]; then
  echo "--prune-min-age must not be empty" >&2
  exit 2
fi
if [[ -z "$RETIRE_MIN_AGE" ]]; then
  echo "--retire-min-age must not be empty" >&2
  exit 2
fi

remote_cmd=""
printf -v remote_cmd \
  "REMOTE_ROOT=%q ON_CALENDAR=%q TIMEOUT=%q APPLY=%q PRUNE_UNMANAGED=%q PRUNE_MIN_AGE=%q RETIRE_STALE_UNMANAGED=%q RETIRE_MIN_AGE=%q bash -s" \
  "$REMOTE_ROOT" "$ON_CALENDAR" "$TIMEOUT" "$APPLY" "$PRUNE_UNMANAGED" "$PRUNE_MIN_AGE" "$RETIRE_STALE_UNMANAGED" "$RETIRE_MIN_AGE"
ssh "$HOST" "$remote_cmd" <<'REMOTE'
set -euo pipefail

install -d /etc/systemd/system

apply_arg=""
if [[ "${APPLY}" == "true" ]]; then
  apply_arg=" -apply"
fi
prune_arg=""
if [[ "${PRUNE_UNMANAGED}" == "true" ]]; then
  prune_arg=" -prune-unmanaged-data-sources -prune-data-source-min-age=\"${PRUNE_MIN_AGE}\""
fi
retire_arg=""
if [[ "${RETIRE_STALE_UNMANAGED}" == "true" ]]; then
  retire_arg=" -retire-stale-unmanaged-data-sources -retire-data-source-min-age=\"${RETIRE_MIN_AGE}\""
fi

cat >/etc/systemd/system/lingniu-go-identity-source-sync.service <<SERVICE
[Unit]
Description=Lingniu Go Identity Source Sync
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
WorkingDirectory=${REMOTE_ROOT}/current
EnvironmentFile=${REMOTE_ROOT}/env/base.env
ExecStart=/bin/sh -c 'exec "${REMOTE_ROOT}/current/identity-import" -sync-data-sources${prune_arg}${retire_arg}${apply_arg} -timeout="${TIMEOUT}"'
TimeoutStartSec=5min
StandardOutput=journal
StandardError=journal
SERVICE

cat >/etc/systemd/system/lingniu-go-identity-source-sync.timer <<TIMER
[Unit]
Description=Run Lingniu Go Identity Source Sync

[Timer]
OnCalendar=${ON_CALENDAR}
AccuracySec=10s
RandomizedDelaySec=10s
Persistent=false
Unit=lingniu-go-identity-source-sync.service

[Install]
WantedBy=timers.target
TIMER

systemctl daemon-reload
systemd-analyze verify /etc/systemd/system/lingniu-go-identity-source-sync.service /etc/systemd/system/lingniu-go-identity-source-sync.timer
systemctl reset-failed lingniu-go-identity-source-sync.service 2>/dev/null || true
systemctl enable --now lingniu-go-identity-source-sync.timer
systemctl start lingniu-go-identity-source-sync.service
systemctl reset-failed lingniu-go-identity-source-sync.service 2>/dev/null || true
systemctl list-timers lingniu-go-identity-source-sync.timer --no-pager
systemctl show lingniu-go-identity-source-sync.service -p Result -p ExecMainStatus -p ActiveState -p SubState --no-pager
REMOTE
