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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SCHEDULE="${DOCS_CRON_SCHEDULE:-17 9 * * *}"
DRY_RUN=0
UNINSTALL=0
MARK_START="# >>> microdao docs maintenance >>>"
MARK_END="# <<< microdao docs maintenance <<<"

usage() {
  cat <<'USAGE'
Usage:
  bash scripts/docs/install_local_cron.sh [--schedule "17 9 * * *"] [--dry-run] [--uninstall]

Default schedule:
  17 9 * * *  (local timezone)

Installs a single managed cron block that runs:
  bash scripts/docs/run_docs_maintenance.sh

No git push is performed by maintenance script.
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --schedule)
      SCHEDULE="$2"
      shift 2
      ;;
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    --uninstall)
      UNINSTALL=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown arg: $1" >&2
      usage
      exit 2
      ;;
  esac
done

if ! command -v crontab >/dev/null 2>&1; then
  echo "crontab command not found" >&2
  exit 3
fi

current="$(crontab -l 2>/dev/null || true)"
cleaned="$(printf '%s\n' "$current" | awk -v s="$MARK_START" -v e="$MARK_END" '
  BEGIN{skip=0}
  index($0,s)>0 {skip=1; next}
  index($0,e)>0 {skip=0; next}
  skip==0 {print}
')"

if [[ "$UNINSTALL" -eq 1 ]]; then
  new_cron="$cleaned"
else
  cmd="cd $ROOT_DIR && mkdir -p docs/consolidation/logs && bash scripts/docs/run_docs_maintenance.sh >> docs/consolidation/logs/cron_runner.log 2>&1"
  block="$MARK_START\n$SCHEDULE $cmd\n$MARK_END"
  if [[ -n "$cleaned" ]]; then
    new_cron="$cleaned\n$block"
  else
    new_cron="$block"
  fi
fi

if [[ "$DRY_RUN" -eq 1 ]]; then
  echo "[dry-run] resulting crontab:"
  printf '%b\n' "$new_cron"
  exit 0
fi

printf '%b\n' "$new_cron" | crontab -

echo "crontab updated"
crontab -l
