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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
LOG_DIR="$ROOT_DIR/docs/consolidation/logs"
STAMP="$(date +%Y%m%d-%H%M%S)"
LOG_FILE="$LOG_DIR/docs_maintenance_${STAMP}.log"
LATEST_LOG="$LOG_DIR/docs_maintenance_latest.log"
DRY_RUN=0

usage() {
  cat <<'USAGE'
Usage:
  bash scripts/docs/run_docs_maintenance.sh [--dry-run]

Steps:
  1) services sync (--apply or --dry-run)
  2) docs lint

No git push is performed.
USAGE
}

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

mkdir -p "$LOG_DIR"

{
  echo "[docs-maintenance] started: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
  echo "[docs-maintenance] repo: $ROOT_DIR"
  if [[ "$DRY_RUN" -eq 1 ]]; then
    echo "[docs-maintenance] mode: dry-run"
    bash "$ROOT_DIR/scripts/docs/services_sync.sh" --dry-run
  else
    echo "[docs-maintenance] mode: apply"
    bash "$ROOT_DIR/scripts/docs/services_sync.sh" --apply
  fi

  echo "[docs-maintenance] lint start"
  bash "$ROOT_DIR/scripts/docs/docs_lint.sh"
  echo "[docs-maintenance] success"
} > "$LOG_FILE" 2>&1

cp "$LOG_FILE" "$LATEST_LOG"
echo "Wrote: $LOG_FILE"
echo "Updated: $LATEST_LOG"
