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

DD_ASSET_BASE_URL="${DD_ASSET_BASE_URL:-https://node1.meday.top/dd_debian12}"
REINSTALL_URL="${DD_ASSET_BASE_URL}/reinstall.upstream.sh"
DEBIAN_PRESEED_URL="${DD_ASSET_BASE_URL}/debian.upstream.cfg"
REINSTALL_SCRIPT_VERSION="4BACD833-A585-23BA-6CBB-9AA4E08E0005"
REINSTALL_UPSTREAM_COMMIT="98f1e21013233d42750cc2e7a298a0818461d686"
REINSTALL_UPSTREAM_URL="https://raw.githubusercontent.com/bin456789/reinstall/${REINSTALL_UPSTREAM_COMMIT}/reinstall.sh"
REINSTALL_UPSTREAM_CDN_URL="https://cdn.jsdelivr.net/gh/bin456789/reinstall@${REINSTALL_UPSTREAM_COMMIT}/reinstall.sh"
DEBIAN_PRESEED_UPSTREAM_URL="https://raw.githubusercontent.com/bin456789/reinstall/${REINSTALL_UPSTREAM_COMMIT}/debian.cfg"
DEBIAN_PRESEED_UPSTREAM_CDN_URL="https://cdn.jsdelivr.net/gh/bin456789/reinstall@${REINSTALL_UPSTREAM_COMMIT}/debian.cfg"
WORK_DIR="/root"
REINSTALL_FILE="${WORK_DIR}/reinstall.sh"

TARGET_OS="debian"
TARGET_VERSION="12"

USERNAME="root"
ROOT_PASSWORD='ppghojsj@66933'
SSH_PORT="22"

# Standalone DD has no per-machine enrollment token; Agent install is opt-in.
AGENT_INSTALL_ENABLED="${AGENT_INSTALL_ENABLED:-0}"
AGENT_INSTALL_URL="${AGENT_INSTALL_URL:-https://node1.meday.top/install-agent.sh}"
AGENT_BINARY_URL="${AGENT_BINARY_URL:-https://node1.meday.top/autochangeip-agent-linux-amd64}"
AGENT_SERVER_URL="${AGENT_SERVER_URL:-https://api.me11.top}"
AGENT_TOKEN="${AGENT_TOKEN:-}"
AGENT_SECRET="${AGENT_SECRET:-}"
AGENT_OPS_USER="${AGENT_OPS_USER:-ops}"
OPS_PASSWORD="${OPS_PASSWORD:-}"
AGENT_ACCOUNT_ID="${AGENT_ACCOUNT_ID:-}"
AGENT_INSTANCE_ID="${AGENT_INSTANCE_ID:-}"
AGENT_MACHINE_ID="${AGENT_MACHINE_ID:-${AGENT_ACCOUNT_ID}${AGENT_ACCOUNT_ID:+-}${AGENT_INSTANCE_ID}}"
AGENT_INSTALLATION_ID="${AGENT_INSTALLATION_ID:-}"
AGENT_INTERVAL="${AGENT_INTERVAL:-30s}"

LOG_FILE="/var/log/dd_reinstall.log"

log() {
  echo "[$(date '+%F %T')] $*" | tee -a "$LOG_FILE"
}

die() {
  log "ERROR: $*"
  exit 1
}

check_root() {
  if [[ "$(id -u)" -ne 0 ]]; then
    die "please run as root"
  fi
}

shell_quote() {
  printf "'%s'" "$(printf "%s" "$1" | sed "s/'/'\\''/g")"
}

validate_agent_settings() {
  if [[ "$AGENT_INSTALL_ENABLED" != "1" && "$AGENT_INSTALL_ENABLED" != "true" ]]; then
    log "Agent first-boot install disabled by AGENT_INSTALL_ENABLED=$AGENT_INSTALL_ENABLED"
    return 0
  fi

  [[ -n "$AGENT_INSTALL_URL" ]] || die "AGENT_INSTALL_URL is required"
  [[ -n "$AGENT_SERVER_URL" ]] || die "AGENT_SERVER_URL is required"
  [[ -n "$AGENT_TOKEN" ]] || die "AGENT_TOKEN is required"
  [[ -n "$AGENT_SECRET" ]] || die "AGENT_SECRET is required"
}

install_tools() {
  log "checking download tools: curl/wget"

  if command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1; then
    return 0
  fi

  log "curl/wget not found, trying to install"

  export DEBIAN_FRONTEND=noninteractive

  if command -v apt-get >/dev/null 2>&1; then
    apt-get update -y
    apt-get install -y curl wget ca-certificates
  elif command -v yum >/dev/null 2>&1; then
    yum install -y curl wget ca-certificates
  elif command -v dnf >/dev/null 2>&1; then
    dnf install -y curl wget ca-certificates
  else
    die "cannot install curl/wget automatically; install curl or wget first"
  fi
}

download_file() {
  local url=$1
  local output=$2

  if command -v curl >/dev/null 2>&1; then
    curl -fLsS --connect-timeout 10 --max-time 60 --speed-limit 1024 --speed-time 20 --retry 1 -o "$output" "$url"
  else
    wget --timeout=20 --tries=2 -O "$output" "$url"
  fi
}

download_reinstall() {
  mkdir -p "$WORK_DIR"
  cd "$WORK_DIR"

  local candidate_url confhome_url matched=0
  for candidate_url in "$REINSTALL_URL" "$REINSTALL_UPSTREAM_URL" "$REINSTALL_UPSTREAM_CDN_URL"; do
    rm -f "$REINSTALL_FILE"
    log "downloading reinstall.sh from $candidate_url"
    if ! download_file "$candidate_url" "$REINSTALL_FILE"; then
      log "download failed; trying next source"
      continue
    fi
    if [[ ! -s "$REINSTALL_FILE" ]]; then
      log "downloaded reinstall.sh is empty; trying next source"
      continue
    fi
    sed -i 's/\r$//' "$REINSTALL_FILE"
    if grep -Fxq "SCRIPT_VERSION=$REINSTALL_SCRIPT_VERSION" "$REINSTALL_FILE"; then
      matched=1
      break
    fi
    log "reinstall.sh version mismatch; trying next source"
    rm -f "$REINSTALL_FILE"
  done

  [[ "$matched" -eq 1 ]] || die "could not download matching reinstall.sh from any source"
  if ! grep -Fxq 'confhome=https://raw.githubusercontent.com/bin456789/reinstall/main' "$REINSTALL_FILE" ||
     ! grep -Fxq 'confhome_cn=https://cnb.cool/bin456789/reinstall/-/git/raw/main' "$REINSTALL_FILE"; then
    die "unexpected reinstall.sh upstream URLs"
  fi
  confhome_url="https://raw.githubusercontent.com/bin456789/reinstall/$REINSTALL_UPSTREAM_COMMIT"
  if [[ "$candidate_url" = "$REINSTALL_UPSTREAM_CDN_URL" ]]; then
    confhome_url="https://cdn.jsdelivr.net/gh/bin456789/reinstall@$REINSTALL_UPSTREAM_COMMIT"
  fi
  sed -i "s|^confhome=.*|confhome=$confhome_url|" "$REINSTALL_FILE"
  sed -i "s|^confhome_cn=.*|confhome_cn=$confhome_url|" "$REINSTALL_FILE"
  chmod +x "$REINSTALL_FILE"

  log "download complete: $REINSTALL_FILE"
}

build_agent_install_env() {
  cat <<EOF
export AGENT_INSTALL_URL=$(shell_quote "$AGENT_INSTALL_URL")
export AGENT_SERVER_URL=$(shell_quote "$AGENT_SERVER_URL")
export AGENT_TOKEN=$(shell_quote "$AGENT_TOKEN")
export AGENT_SECRET=$(shell_quote "$AGENT_SECRET")
export AGENT_OPS_USER=$(shell_quote "$AGENT_OPS_USER")
export OPS_USER=$(shell_quote "$AGENT_OPS_USER")
export AGENT_INTERVAL=$(shell_quote "$AGENT_INTERVAL")
EOF

  if [[ -n "$AGENT_ACCOUNT_ID" ]]; then
    echo "export AGENT_ACCOUNT_ID=$(shell_quote "$AGENT_ACCOUNT_ID")"
  fi
  if [[ -n "$AGENT_INSTANCE_ID" ]]; then
    echo "export AGENT_INSTANCE_ID=$(shell_quote "$AGENT_INSTANCE_ID")"
  fi
  if [[ -n "$AGENT_MACHINE_ID" ]]; then
    echo "export AGENT_MACHINE_ID=$(shell_quote "$AGENT_MACHINE_ID")"
  fi
  if [[ -n "$AGENT_INSTALLATION_ID" ]]; then
    echo "export AGENT_INSTALLATION_ID=$(shell_quote "$AGENT_INSTALLATION_ID")"
  fi
  if [[ -n "$AGENT_BINARY_URL" ]]; then
    echo "export AGENT_BINARY_URL=$(shell_quote "$AGENT_BINARY_URL")"
  fi
  if [[ -n "$OPS_PASSWORD" ]]; then
    echo "export OPS_PASSWORD=$(shell_quote "$OPS_PASSWORD")"
  fi
}

create_agent_firstboot_payload() {
  local payload="$WORK_DIR/autochangeip-agent-firstboot.sh"
  local env_block
  env_block="$(build_agent_install_env)"

  cat >"$payload" <<EOF
#!/bin/sh
set -eu

os_dir="\${1:-/target}"
mkdir -p "\$os_dir/usr/local/sbin" "\$os_dir/etc/systemd/system"

cat >"\$os_dir/usr/local/sbin/autochangeip-agent-firstboot.sh" <<'SCRIPT'
#!/bin/sh
set -eu
LOG=/var/log/autochangeip-agent-firstboot.log
exec >>"\$LOG" 2>&1

echo "[\$(date '+%F %T')] autochangeip-agent first boot install start"

$env_block

if command -v curl >/dev/null 2>&1; then
  curl -fsSL "\$AGENT_INSTALL_URL" | sh
elif command -v wget >/dev/null 2>&1; then
  wget -qO- "\$AGENT_INSTALL_URL" | sh
else
  echo "curl/wget not found, trying apt-get install"
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -y
  apt-get install -y curl wget ca-certificates
  curl -fsSL "\$AGENT_INSTALL_URL" | sh
fi

systemctl disable autochangeip-agent-firstboot.service || true
rm -f /etc/systemd/system/multi-user.target.wants/autochangeip-agent-firstboot.service
rm -f /etc/systemd/system/autochangeip-agent-firstboot.service
rm -f /usr/lib/systemd/system-preset/01-autochangeip-agent-firstboot.preset
rm -f /lib/systemd/system-preset/01-autochangeip-agent-firstboot.preset
rm -f /usr/local/sbin/autochangeip-agent-firstboot.sh

echo "[\$(date '+%F %T')] autochangeip-agent first boot install complete"
SCRIPT
chmod 0755 "\$os_dir/usr/local/sbin/autochangeip-agent-firstboot.sh"

cat >"\$os_dir/etc/systemd/system/autochangeip-agent-firstboot.service" <<'SERVICE'
[Unit]
Description=Install AutoChangeIP Agent on first boot
After=network-online.target
Wants=network-online.target
ConditionPathExists=/usr/local/sbin/autochangeip-agent-firstboot.sh

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/autochangeip-agent-firstboot.sh
RemainAfterExit=no

[Install]
WantedBy=multi-user.target
SERVICE

mkdir -p "\$os_dir/etc/systemd/system/multi-user.target.wants"
ln -sf /etc/systemd/system/autochangeip-agent-firstboot.service "\$os_dir/etc/systemd/system/multi-user.target.wants/autochangeip-agent-firstboot.service"

if [ -d "\$os_dir/usr/lib/systemd/system-preset" ]; then
  echo "enable autochangeip-agent-firstboot.service" >"\$os_dir/usr/lib/systemd/system-preset/01-autochangeip-agent-firstboot.preset"
elif [ -d "\$os_dir/lib/systemd/system-preset" ]; then
  echo "enable autochangeip-agent-firstboot.service" >"\$os_dir/lib/systemd/system-preset/01-autochangeip-agent-firstboot.preset"
fi
EOF

  chmod 0700 "$payload"
  echo "$payload"
}

create_custom_debian_preseed() {
  local preseed="$WORK_DIR/debian-autochangeip.cfg"
  local candidate_url matched=0

  for candidate_url in "$DEBIAN_PRESEED_URL" "$DEBIAN_PRESEED_UPSTREAM_URL" "$DEBIAN_PRESEED_UPSTREAM_CDN_URL"; do
    rm -f "$preseed"
    log "downloading debian preseed from $candidate_url" >&2
    if ! download_file "$candidate_url" "$preseed"; then
      log "preseed download failed; trying next source" >&2
      continue
    fi
    if [[ ! -s "$preseed" ]]; then
      log "downloaded preseed is empty; trying next source" >&2
      continue
    fi
    sed -i 's/\r$//' "$preseed"
    if grep -q '^d-i preseed/late_command string' "$preseed" &&
       [[ $(grep -c '^[[:space:]]*in-target systemctl enable fix-eth-name' "$preseed") -eq 1 ]]; then
      matched=1
      break
    fi
    log "unexpected debian.cfg layout; trying next source" >&2
  done

  [[ "$matched" -eq 1 ]] || die "could not download compatible debian.cfg from any source"

  awk '
    /^[[:space:]]*in-target systemctl enable fix-eth-name/ {
      print "    if [ -f /configs/autochangeip-agent-firstboot.sh ]; then sh /configs/autochangeip-agent-firstboot.sh /target; fi; \\"
    }
    { print }
  ' "$preseed" >"${preseed}.patched"
  mv "${preseed}.patched" "$preseed"

  echo "$preseed"
}

patch_reinstall_for_agent_firstboot() {
  if [[ "$AGENT_INSTALL_ENABLED" != "1" && "$AGENT_INSTALL_ENABLED" != "true" ]]; then
    return 0
  fi

  local payload preseed marker
  payload="$(create_agent_firstboot_payload)"
  preseed="$(create_custom_debian_preseed)"

  if ! grep -q 'nextos_cmdline+=" url=$nextos_ks"' "$REINSTALL_FILE"; then
    die "unexpected reinstall.sh: missing Debian preseed URL anchor"
  fi

  sed -i 's|nextos_cmdline+=" url=$nextos_ks"|nextos_cmdline+=" file=/preseed.cfg"|' "$REINSTALL_FILE"

  marker="$(mktemp)"
  cat >"$marker" <<EOF
    cp '$payload' \$initrd_dir/configs/autochangeip-agent-firstboot.sh
    cp '$preseed' \$initrd_dir/preseed.cfg
EOF
  if [[ $(grep -c '^[[:space:]]*mkdir -p \$initrd_dir/configs$' "$REINSTALL_FILE") -ne 1 ]]; then
    die "unexpected reinstall.sh: missing initrd configs anchor"
  fi
  sed -i "/^[[:space:]]*mkdir -p \$initrd_dir\/configs$/r $marker" "$REINSTALL_FILE"
  rm -f "$marker"

  log "patched reinstall.sh to use initrd preseed and install Agent on first boot"
}

run_reinstall() {
  cd "$WORK_DIR"

  log "starting DD reinstall"
  log "target OS: ${TARGET_OS} ${TARGET_VERSION}"
  log "username: ${USERNAME}"
  log "SSH port: ${SSH_PORT}"

  bash "$REINSTALL_FILE" "$TARGET_OS" "$TARGET_VERSION" \
    --username "$USERNAME" \
    --password "$ROOT_PASSWORD" \
    --ssh-port "$SSH_PORT"

  log "reinstall.sh setup complete; installer will auto reboot when finished"
}

reboot_server() {
  log "rebooting server to start reinstall"
  sync
  sleep 3

  if command -v systemctl >/dev/null 2>&1; then
    systemctl reboot -i
  else
    reboot
  fi
}

main() {
  log "========== start DD reinstall task =========="

  check_root
  validate_agent_settings
  install_tools
  download_reinstall
  patch_reinstall_for_agent_firstboot
  run_reinstall
  reboot_server
}

main "$@"
