#!/usr/bin/env bash
# Local-only orchestrator for the current P0 110 control path + Harbor blocker.
#
# Run on host 110 from a trusted local console or an already working root shell.
# Default mode is read-only. Apply modes do not read key material, do not create
# keys, do not restart the Docker daemon, and do not reboot the host.

set -euo pipefail

MODE="check"
REQUESTED_MODE="--check"
TARGET_USER="${TARGET_USER:-wooo}"
EXPECTED_HOST_IP="${AWOOOI_110_EXPECTED_HOST_IP:-192.168.0.110}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SSH_REPAIR_SCRIPT="${AWOOOI_110_SSH_REPAIR_SCRIPT:-}"
HARBOR_WATCHDOG_SCRIPT="${AWOOOI_HARBOR_WATCHDOG_SCRIPT:-}"
CONTROLLED_LANE_VERIFIER_SCRIPT="${AWOOOI_110_CONTROLLED_LANE_VERIFIER_SCRIPT:-}"
RELOAD_SSH="${RELOAD_SSH:-0}"

usage() {
  cat <<'USAGE'
Usage: recover-110-control-path-and-harbor-local.sh [--check|--apply-ssh-metadata|--apply-ssh-control-path|--repair-harbor-once|--apply-all]

Modes:
  --check               Read-only checks for SSH metadata, Harbor readiness, and controlled CD lane readiness.
  --apply-ssh-metadata  Fix TARGET_USER home/.ssh/authorized_keys metadata only.
  --apply-ssh-control-path
                        AI Loop alias for --apply-ssh-metadata.
  --repair-harbor-once  Run one bounded Harbor watchdog repair cycle only.
  --apply-all           Apply SSH metadata repair, then one Harbor repair cycle.

Environment:
  TARGET_USER=wooo
  RELOAD_SSH=0
  ALLOW_NON_110=0

Safety:
  This script refuses to apply outside 192.168.0.110 unless ALLOW_NON_110=1.
USAGE
}

while [ "$#" -gt 0 ]; do
  case "$1" in
	    --check)
	      MODE="check"
	      REQUESTED_MODE="$1"
	      ;;
	    --apply-ssh-metadata|--apply-ssh-control-path)
	      MODE="apply_ssh_metadata"
	      REQUESTED_MODE="$1"
	      ;;
	    --repair-harbor-once)
	      MODE="repair_harbor_once"
	      REQUESTED_MODE="$1"
	      ;;
	    --apply-all)
	      MODE="apply_all"
	      REQUESTED_MODE="$1"
	      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 64
      ;;
  esac
  shift
done

log() {
  printf '[%s] [recover-110] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"
}

host_has_expected_ip() {
  if command -v hostname >/dev/null 2>&1; then
    hostname -I 2>/dev/null | tr ' ' '\n' | grep -qx "$EXPECTED_HOST_IP" && return 0
  fi
  if command -v ip >/dev/null 2>&1; then
    ip -o -4 addr show 2>/dev/null | grep -q " ${EXPECTED_HOST_IP}/" && return 0
  fi
  return 1
}

require_expected_host_for_apply() {
  if [ "${ALLOW_NON_110:-0}" = "1" ]; then
    log "ALLOW_NON_110=1 set; expected host guard bypassed"
    return 0
  fi
  if host_has_expected_ip; then
    return 0
  fi
  echo "BLOCKED not running on ${EXPECTED_HOST_IP}; use 110 local console/root shell" >&2
  exit 65
}

resolve_ssh_repair_script() {
  if [ -n "$SSH_REPAIR_SCRIPT" ] && [ -x "$SSH_REPAIR_SCRIPT" ]; then
    printf '%s\n' "$SSH_REPAIR_SCRIPT"
    return 0
  fi
  if [ -x "$SCRIPT_DIR/repair-110-ssh-publickey-auth-local.sh" ]; then
    printf '%s\n' "$SCRIPT_DIR/repair-110-ssh-publickey-auth-local.sh"
    return 0
  fi
  if [ -x "/usr/local/bin/repair-110-ssh-publickey-auth-local.sh" ]; then
    printf '%s\n' "/usr/local/bin/repair-110-ssh-publickey-auth-local.sh"
    return 0
  fi
  return 1
}

resolve_harbor_watchdog_script() {
  if [ -n "$HARBOR_WATCHDOG_SCRIPT" ] && [ -x "$HARBOR_WATCHDOG_SCRIPT" ]; then
    printf '%s\n' "$HARBOR_WATCHDOG_SCRIPT"
    return 0
  fi
  if [ -x "/usr/local/bin/harbor-watchdog.sh" ]; then
    printf '%s\n' "/usr/local/bin/harbor-watchdog.sh"
    return 0
  fi
  if [ -x "$SCRIPT_DIR/harbor-watchdog.sh" ]; then
    printf '%s\n' "$SCRIPT_DIR/harbor-watchdog.sh"
    return 0
  fi
  return 1
}

resolve_controlled_lane_verifier_script() {
  if [ -n "$CONTROLLED_LANE_VERIFIER_SCRIPT" ] && [ -x "$CONTROLLED_LANE_VERIFIER_SCRIPT" ]; then
    printf '%s\n' "$CONTROLLED_LANE_VERIFIER_SCRIPT"
    return 0
  fi
  if [ -x "/usr/local/bin/check-awoooi-110-controlled-cd-lane-readiness.sh" ]; then
    printf '%s\n' "/usr/local/bin/check-awoooi-110-controlled-cd-lane-readiness.sh"
    return 0
  fi
  if [ -x "$SCRIPT_DIR/../../ops/runner/check-awoooi-110-controlled-cd-lane-readiness.sh" ]; then
    printf '%s\n' "$SCRIPT_DIR/../../ops/runner/check-awoooi-110-controlled-cd-lane-readiness.sh"
    return 0
  fi
  return 1
}

run_ssh_check() {
  local script
  if ! script="$(resolve_ssh_repair_script)"; then
    echo "SSH_REPAIR_SCRIPT_STATUS=missing"
    return 1
  fi
  TARGET_USER="$TARGET_USER" RELOAD_SSH=0 "$script" --check
}

run_ssh_apply() {
  local script
  require_expected_host_for_apply
  if ! script="$(resolve_ssh_repair_script)"; then
    echo "SSH_REPAIR_SCRIPT_STATUS=missing"
    return 1
  fi
  TARGET_USER="$TARGET_USER" RELOAD_SSH="$RELOAD_SSH" "$script" --apply
}

run_harbor_check() {
  local script
  if ! script="$(resolve_harbor_watchdog_script)"; then
    echo "HARBOR_WATCHDOG_SCRIPT_STATUS=missing"
    return 1
  fi
  "$script" --check
}

run_harbor_repair_once() {
  local script
  require_expected_host_for_apply
  if ! script="$(resolve_harbor_watchdog_script)"; then
    echo "HARBOR_WATCHDOG_SCRIPT_STATUS=missing"
    return 1
  fi
  "$script" --repair-once
}

run_controlled_lane_check() {
  local script
  if ! script="$(resolve_controlled_lane_verifier_script)"; then
    echo "CONTROLLED_LANE_VERIFIER_SCRIPT_STATUS=missing"
    return 1
  fi
  TARGET_HOST_IP="$EXPECTED_HOST_IP" "$script"
}

echo "AWOOOI_110_CONTROL_PATH_AND_HARBOR_LOCAL_RECOVERY mode=${MODE} requested_mode=${REQUESTED_MODE} target_user=${TARGET_USER}"
echo "expected_host_ip=${EXPECTED_HOST_IP}"
echo "ssh_publickey_auth_stall_recovery_supported=true"
echo "ssh_control_path_apply_alias_supported=true"
echo "ssh_control_path_apply_alias=--apply-ssh-control-path"
echo "ssh_control_path_apply_canonical_mode=--apply-ssh-metadata"
echo "local_console_required_for_apply=true"
echo "operation_boundary_secret_value_read=false"
echo "operation_boundary_runner_token_read=false"
echo "operation_boundary_raw_runner_registration_read=false"
echo "operation_boundary_authorized_keys_content_printed=false"
echo "operation_boundary_ssh_key_material_created=false"
echo "operation_boundary_host_reboot_performed=false"
echo "operation_boundary_docker_daemon_restart_performed=false"
echo "operation_boundary_node_drain_performed=false"

case "$MODE" in
  check)
    run_ssh_check || true
    run_harbor_check || true
    run_controlled_lane_check || true
    ;;
  apply_ssh_metadata)
    run_ssh_apply
    ;;
  repair_harbor_once)
    run_harbor_repair_once
    ;;
  apply_all)
    run_ssh_apply
    run_harbor_repair_once
    run_controlled_lane_check || true
    ;;
  *)
    echo "Unknown internal mode: $MODE" >&2
    exit 64
    ;;
esac
