#!/usr/bin/env bash
# RSPC first installation.
#
#   sudo ./scripts/install.sh
#
# Non-interactive: RSPC_DOMAIN=panel.example.com RSPC_EMAIL=me@example.com [RSPC_PANEL_PORT=9440] \
#                  [RSPC_ACME_STAGING=1] [RSPC_YES=1] sudo -E ./scripts/install.sh
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"

require_root
require_ubuntu
is_installed && die "RSPC is already installed ($(installed_version)). Use update.sh to upgrade or uninstall.sh to remove."

NEW_VERSION=$(cat "$SRC_DIR/VERSION")
echo "${C_BOLD}RSPC (ReveServerProx-Controling) $NEW_VERSION — installation${C_RESET}"
echo
verify_checksums

# --- ports 80/443 must be free ---
for p in 80 443; do
  owner=$(port_owner tcp "$p")
  [[ -z $owner ]] || die "TCP port $p is used by '$owner'. Stop it first (e.g. systemctl disable --now $owner) — RSPC must own ports 80 and 443."
done
ok "ports 80 and 443 are free"

# --- questions ---
DOMAIN=${RSPC_DOMAIN:-}
while true; do
  [[ -n $DOMAIN ]] || ask DOMAIN "Panel domain (e.g. panel.example.com)"
  DOMAIN=$(echo "$DOMAIN" | tr '[:upper:]' '[:lower:]' | sed 's/\.$//')
  valid_domain "$DOMAIN" && break
  warn "'$DOMAIN' is not a valid domain name"
  [[ -z ${RSPC_DOMAIN:-} ]] || exit 1
  DOMAIN=""
done

PANEL_PORT=${RSPC_PANEL_PORT:-}
while true; do
  [[ -n $PANEL_PORT ]] || ask PANEL_PORT "Internal panel port (loopback only, not exposed to the internet)" 9440
  if [[ $PANEL_PORT =~ ^[0-9]+$ ]] && ((PANEL_PORT >= 1024 && PANEL_PORT <= 65535)); then
    owner=$(port_owner tcp "$PANEL_PORT")
    [[ -z $owner ]] && break
    warn "port $PANEL_PORT is used by '$owner'"
  else
    warn "port must be a number between 1024 and 65535"
  fi
  [[ -z ${RSPC_PANEL_PORT:-} ]] || exit 1
  PANEL_PORT=""
done

EMAIL=${RSPC_EMAIL:-}
while true; do
  [[ -n $EMAIL ]] || ask EMAIL "E-mail for Let's Encrypt (expiry notices)"
  valid_email "$EMAIL" && break
  warn "'$EMAIL' is not a valid e-mail"
  [[ -z ${RSPC_EMAIL:-} ]] || exit 1
  EMAIL=""
done

# --- DNS sanity check ---
info "checking DNS for $DOMAIN"
mapfile -t DNS_IPS < <(getent ahosts "$DOMAIN" 2>/dev/null | awk '{print $1}' | sort -u)
mapfile -t LOCAL_IPS < <(hostname -I 2>/dev/null | tr ' ' '\n' | sed '/^$/d')
if ((${#DNS_IPS[@]} == 0)); then
  warn "$DOMAIN does not resolve yet. The certificate will be issued automatically once DNS points to this server."
  [[ ${RSPC_YES:-0} == 1 ]] || confirm "Continue anyway?" || exit 1
else
  match=0
  for ip in "${DNS_IPS[@]}"; do
    for l in "${LOCAL_IPS[@]}"; do [[ $ip == "$l" ]] && match=1; done
  done
  if ((match)); then
    ok "$DOMAIN → ${DNS_IPS[*]} (this server)"
  else
    warn "$DOMAIN resolves to ${DNS_IPS[*]}, local addresses are ${LOCAL_IPS[*]:-none}."
    warn "That is fine behind 1:1 NAT (cloud public IP); otherwise fix the A/AAAA record."
    [[ ${RSPC_YES:-0} == 1 ]] || confirm "Continue?" || exit 1
  fi
fi

echo
echo "  Panel:        https://$DOMAIN"
echo "  Panel port:   127.0.0.1:$PANEL_PORT (loopback)"
echo "  ACME e-mail:  $EMAIL"
[[ ${RSPC_ACME_STAGING:-0} == 1 ]] && echo "  ACME:         Let's Encrypt STAGING (test certificates)"
echo
[[ ${RSPC_YES:-0} == 1 ]] || confirm "Install with these settings?" || exit 1

# --- user & directories ---
if ! id "$RSPC_USER" &>/dev/null; then
  useradd --system --home-dir "$RSPC_DATA" --no-create-home --shell /usr/sbin/nologin "$RSPC_USER"
  ok "system user '$RSPC_USER' created"
fi
install -d -m 0750 -o root -g "$RSPC_USER" "$RSPC_ETC"
install -d -m 0750 -o "$RSPC_USER" -g "$RSPC_USER" "$RSPC_DATA" "$RSPC_BACKUPS"

install_files "$SRC_DIR"
ok "files installed to $RSPC_HOME"

STAGING=false
[[ ${RSPC_ACME_STAGING:-0} == 1 ]] && STAGING=true
umask 027
cat >"$RSPC_CONFIG" <<EOF
# RSPC configuration. Restart after changes: sudo $RSPC_HOME/scripts/restart.sh
role: all-in-one
node_id: local
data_dir: $RSPC_DATA

panel:
  domain: $DOMAIN
  port: $PANEL_PORT

acme:
  email: $EMAIL
  staging: $STAGING

proxy:
  http_listen: ":80"
  https_listen: ":443"
  port_pool_start: 20000
  port_pool_end: 29999
  udp_idle_timeout: 120
EOF
chown root:"$RSPC_USER" "$RSPC_CONFIG"
chmod 0640 "$RSPC_CONFIG"
umask 022
ok "config written to $RSPC_CONFIG"

rspc_cli init >/dev/null
ok "database initialized"

if ufw_active; then
  ufw allow 80/tcp >/dev/null
  ufw allow 443/tcp >/dev/null
  ok "ufw: opened 80/tcp and 443/tcp"
fi

write_unit
systemctl enable --now "$RSPC_SERVICE" >/dev/null 2>&1
info "starting service"
if ! wait_healthy 30; then
  show_recent_logs 40
  die "service did not become healthy. Fix the problem above, then run: sudo $RSPC_HOME/scripts/start.sh"
fi
ok "service is running"

# No token if accounts already exist (reinstall over kept data).
if TOKEN=$(rspc_cli setup-token 2>/dev/null); then :; else TOKEN=""; fi

info "waiting for the Let's Encrypt certificate for $DOMAIN (up to 90 s)"
CERT="pending"
for _ in $(seq 1 45); do
  if out=$(rspc_cli cert-status 2>&1); then rc=0; else rc=$?; fi
  if ((rc == 0)); then CERT="ok: $out"; break; fi
  if ((rc == 1)); then CERT="error: ${out#error: }"; break; fi
  sleep 2
done
case $CERT in
  ok:*) ok "certificate issued (${CERT#ok: })" ;;
  error:*) warn "certificate not issued yet: ${CERT#error: }"; warn "RSPC keeps retrying automatically. Check DNS and that ports 80/443 are reachable from the internet." ;;
  *) warn "certificate is still being issued — RSPC keeps trying in the background." ;;
esac

echo
echo "${C_GREEN}${C_BOLD}RSPC $NEW_VERSION installed.${C_RESET}"
echo
echo "  Panel URL:          ${C_BOLD}https://$DOMAIN${C_RESET}"
if [[ -n $TOKEN ]]; then
  cat <<EOF
  One-time token:     ${C_BOLD}$TOKEN${C_RESET}
                      valid 24 hours, single use. It is shown only now.

  Open the panel, enter the token, create the superadmin account and
  link an authenticator app (2FA is mandatory).

  Lost the token?     sudo $RSPC_HOME/scripts/reset-setup-token.sh
EOF
else
  echo "  Existing data found in $RSPC_DATA — sign in with your existing account."
fi
cat <<EOF

  Manage service:     sudo $RSPC_HOME/scripts/{start,stop,restart,status,logs,update,uninstall}.sh
  Emergency access:   ssh -L $PANEL_PORT:127.0.0.1:$PANEL_PORT <server>  →  http://127.0.0.1:$PANEL_PORT
EOF
