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

STATE_DIR="/var/lib/harresi"
REQUIRED_FILE="$STATE_DIR/initial-date.required"
DONE_FILE="$STATE_DIR/initial-date.done"
LOG_DIR="/var/log/harresi"
LOG_FILE="$LOG_DIR/initial-date.log"
TIMEZONE="Europe/Madrid"
MIN_EPOCH="1704067200"

log() {
  local message="$1"
  install -d -m 0755 -o root -g root "$LOG_DIR"
  printf '[%s] %s\n' "$(date -Iseconds 2>/dev/null || date)" "$message" >> "$LOG_FILE" 2>/dev/null || true
  logger -t harresi-initial-date -- "$message" 2>/dev/null || true
}

require_root() {
  if [ "${EUID:-$(id -u)}" -ne 0 ]; then
    echo "Este asistente debe ejecutarse como root." >&2
    exit 1
  fi
}

mark_required() {
  install -d -m 0755 -o root -g root "$STATE_DIR"
  if [ ! -e "$DONE_FILE" ]; then
    install -m 0644 -o root -g root /dev/null "$REQUIRED_FILE"
    log "Configuracion manual inicial de fecha marcada como requerida"
  fi
}

is_required() {
  [ -e "$REQUIRED_FILE" ] && [ ! -e "$DONE_FILE" ]
}

parse_epoch() {
  local value="$1"
  local epoch

  epoch="$(TZ="$TIMEZONE" date -d "$value" +%s 2>/dev/null || true)"
  if [ -z "$epoch" ] || ! [[ "$epoch" =~ ^[0-9]+$ ]]; then
    return 1
  fi
  if [ "$epoch" -lt "$MIN_EPOCH" ]; then
    return 1
  fi

  printf '%s\n' "$epoch"
}

set_manual_time() {
  local epoch="$1"

  timedatectl set-ntp false >/dev/null 2>&1 || true
  timedatectl set-timezone "$TIMEZONE" >/dev/null 2>&1 || true
  date -s "@$epoch" >/dev/null
  hwclock --systohc --utc >/dev/null 2>&1 || true
}

prompt_for_date() {
  local input
  local epoch
  local formatted

  if [ ! -t 0 ]; then
    echo "La configuracion inicial de fecha requiere un terminal interactivo." >&2
    exit 1
  fi

  timedatectl set-timezone "$TIMEZONE" >/dev/null 2>&1 || true
  clear 2>/dev/null || true
  cat <<EOF
Configuracion inicial de fecha de Harresi

Este dispositivo no tiene bateria RTC. El reloj del sistema debe
configurarse manualmente en el primer arranque antes de confiar en
actualizaciones HTTPS, certificados y logs.

Zona horaria: $TIMEZONE
Ejemplo: 2026-07-03 14:30
EOF

  while :; do
    printf '\nIntroduzca la fecha y hora local actual [YYYY-MM-DD HH:MM[:SS]]: '
    IFS= read -r input
    input="${input#"${input%%[![:space:]]*}"}"
    input="${input%"${input##*[![:space:]]}"}"

    if [ -z "$input" ]; then
      echo "La fecha/hora no puede estar vacia."
      continue
    fi

    if ! epoch="$(parse_epoch "$input")"; then
      echo "Fecha/hora no valida. Use una fecha valida desde 2024-01-01 en adelante."
      continue
    fi

    formatted="$(TZ="$TIMEZONE" date -d "@$epoch" '+%Y-%m-%d %H:%M:%S %Z')"
    printf 'Aplicar la hora del sistema "%s"? [s/N]: ' "$formatted"
    IFS= read -r confirm
    case "$confirm" in
      s|S|si|SI|Si|sí|Sí|y|Y|yes|YES)
        set_manual_time "$epoch"
        install -d -m 0755 -o root -g root "$STATE_DIR"
        printf 'configured_at=%s\nconfigured_by=%s\n' \
          "$(date -Iseconds)" \
          "${SUDO_USER:-root}" > "$DONE_FILE"
        chmod 0644 "$DONE_FILE"
        rm -f "$REQUIRED_FILE"
        log "Fecha inicial del sistema configurada manualmente por ${SUDO_USER:-root}: $formatted"
        systemctl --no-block start harresi-http-time-sync.service >/dev/null 2>&1 || true
        echo "Fecha del sistema configurada."
        sleep 2
        return 0
        ;;
      *)
        echo "No aplicado."
        ;;
    esac
  done
}

main() {
  require_root

  case "${1:-}" in
    --mark-required)
      mark_required
      return 0
      ;;
    --required)
      is_required
      return $?
      ;;
    "")
      if ! is_required; then
        return 0
      fi
      prompt_for_date
      ;;
    *)
      echo "Uso: $0 [--mark-required|--required]" >&2
      exit 2
      ;;
  esac
}

main "$@"
