#!/usr/bin/env bash
# ==============================================================================
#  🚀 NginxForge One-Line Quick Installer
#  Usage: curl -fsSL https://get.nginxforge.dev | bash
#         or ./install.sh [-y] [--dry-run]
# ==============================================================================

set -e

COLOR_RESET="\033[0m"
COLOR_GREEN="\033[32m"
COLOR_YELLOW="\033[33m"
COLOR_CYAN="\033[36m"
COLOR_RED="\033[31m"
COLOR_BOLD="\033[1m"

INSTALL_DIR="/var/lib/nginxforge/app"
SERVICE_NAME="nginxforge.service"
PORT="3222"

echo -e "\n================================================================="
echo -e " ${COLOR_BOLD}🚀 NGINXFORGE PRODUCTION VPS QUICK INSTALLER${COLOR_RESET} "
echo -e "=================================================================\n"

# 1. Root / Sudo Check
if [ "$EUID" -ne 0 ]; then
  if command -v sudo >/dev/null 2>&1; then
    SUDO="sudo"
  else
    echo -e "${COLOR_RED}✖ Error: This installer must be run as root or with sudo privileges.${COLOR_RESET}"
    exit 1
  fi
else
  SUDO=""
fi

# 2. Detect OS & Package Manager
echo -e "${COLOR_CYAN}ℹ Detecting Linux distribution and package manager...${COLOR_RESET}"
if [ -f /etc/os-release ]; then
  . /etc/os-release
  OS=$ID
  VERSION=$VERSION_ID
else
  OS=$(uname -s | tr '[:upper:]' '[:lower:]')
fi

echo -e "${COLOR_GREEN}✔ Detected OS:${COLOR_RESET} ${COLOR_BOLD}$PRETTY_NAME ($OS $VERSION)${COLOR_RESET}\n"

# 3. Ensure Node.js & Git Are Installed
if ! command -v git >/dev/null 2>&1; then
  echo -e "${COLOR_YELLOW}⚠ Git is not installed. Installing Git...${COLOR_RESET}"
  if [ "$OS" = "ubuntu" ] || [ "$OS" = "debian" ]; then
    $SUDO apt-get update -y && $SUDO apt-get install -y git curl
  elif [ "$OS" = "centos" ] || [ "$OS" = "rhel" ] || [ "$OS" = "fedora" ] || [ "$OS" = "rocky" ] || [ "$OS" = "almalinux" ]; then
    $SUDO dnf install -y git curl || $SUDO yum install -y git curl
  elif [ "$OS" = "arch" ]; then
    $SUDO pacman -Sy --noconfirm git curl
  elif [ "$OS" = "alpine" ]; then
    $SUDO apk add git curl bash
  fi
fi

if ! command -v node >/dev/null 2>&1; then
  echo -e "${COLOR_YELLOW}⚠ Node.js is not installed. Installing Node.js LTS (v22)...${COLOR_RESET}"
  if [ "$OS" = "ubuntu" ] || [ "$OS" = "debian" ]; then
    curl -fsSL https://deb.nodesource.com/setup_22.x | $SUDO bash -
    $SUDO apt-get install -y nodejs
  elif [ "$OS" = "centos" ] || [ "$OS" = "rhel" ] || [ "$OS" = "fedora" ] || [ "$OS" = "rocky" ] || [ "$OS" = "almalinux" ]; then
    curl -fsSL https://rpm.nodesource.com/setup_22.x | $SUDO bash -
    $SUDO dnf install -y nodejs || $SUDO yum install -y nodejs
  elif [ "$OS" = "arch" ]; then
    $SUDO pacman -Sy --noconfirm nodejs npm
  elif [ "$OS" = "alpine" ]; then
    $SUDO apk add nodejs npm
  fi
fi

# Ensure pnpm is available
if ! command -v pnpm >/dev/null 2>&1; then
  echo -e "${COLOR_CYAN}ℹ Installing pnpm...${COLOR_RESET}"
  $SUDO npm install -g pnpm >/dev/null 2>&1 || true
fi

# 4. Determine App Directory & Install Dependencies
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_DIR=""

if [ -f "$SCRIPT_DIR/package.json" ]; then
  APP_DIR="$SCRIPT_DIR"
else
  APP_DIR="$INSTALL_DIR"
  echo -e "${COLOR_CYAN}ℹ Cloning NginxForge into $INSTALL_DIR...${COLOR_RESET}"
  $SUDO mkdir -p "$INSTALL_DIR"
  if [ ! -d "$INSTALL_DIR/.git" ]; then
    $SUDO git clone https://github.com/nginxforge/nginxforge.git "$INSTALL_DIR"
  else
    (cd "$INSTALL_DIR" && $SUDO git pull || true)
  fi
fi

# 5. Run System Dependencies & Tools Installer
if [ -f "$APP_DIR/scripts/system-installer.mjs" ]; then
  node "$APP_DIR/scripts/system-installer.mjs" "$@"
fi

# 6. Install Node Modules & Build Production Bundle
echo -e "\n${COLOR_CYAN}ℹ Building NginxForge production control plane bundle...${COLOR_RESET}"
(
  cd "$APP_DIR"
  if command -v pnpm >/dev/null 2>&1; then
    pnpm install --frozen-lockfile 2>/dev/null || pnpm install
    pnpm build
  else
    npm install
    npm run build
  fi
)

# 7. Configure & Enable Systemd Service Automatically
NODE_BIN=""
for n in "/usr/bin/node" "/usr/local/bin/node" "/bin/node" "$(command -v node 2>/dev/null)"; do
  if [ -n "$n" ] && [ -x "$n" ] && [[ "$n" != *".hermes"* ]]; then
    NODE_BIN="$n"
    break
  fi
done
[ -z "$NODE_BIN" ] && NODE_BIN=$(command -v node || echo "/usr/bin/node")

SERVICE_FILE="/etc/systemd/system/nginxforge.service"

echo -e "${COLOR_CYAN}ℹ Registering and starting background service ($SERVICE_NAME)...${COLOR_RESET}"
$SUDO bash -c "cat << EOF > $SERVICE_FILE
[Unit]
Description=NginxForge Production Control Plane
After=network.target nginx.service

[Service]
Type=simple
User=root
WorkingDirectory=$APP_DIR
ExecStart=$NODE_BIN $APP_DIR/dist/index.js
Restart=always
RestartSec=3
Environment=NODE_ENV=production
Environment=PORT=3222
Environment=NODE_PATH=$APP_DIR/node_modules
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$(dirname $NODE_BIN)

[Install]
WantedBy=multi-user.target
EOF"

if command -v systemctl >/dev/null 2>&1; then
  $SUDO systemctl daemon-reload
  $SUDO systemctl enable --now nginxforge.service
  $SUDO systemctl restart nginxforge.service
fi

# 8. Detect Public IP Address
SERVER_IP=$(curl -s4 --max-time 3 https://api.ipify.org 2>/dev/null || curl -s4 --max-time 3 https://ifconfig.me 2>/dev/null || hostname -I | awk '{print $1}')
[ -z "$SERVER_IP" ] && SERVER_IP="YOUR-SERVER-IP"

echo -e "\n================================================================="
echo -e " ${COLOR_GREEN}✔ NGINXFORGE ACTIVE & RUNNING AUTOMATICALLY!${COLOR_RESET} "
echo -e "=================================================================\n"
echo -e "Access your NginxForge dashboard at:"
echo -e "  🌐 ${COLOR_BOLD}${COLOR_GREEN}http://${SERVER_IP}:3222${COLOR_RESET}\n"
echo -e "Management Commands:"
echo -e "  • Status:     ${COLOR_CYAN}systemctl status nginxforge${COLOR_RESET}"
echo -e "  • Restart:    ${COLOR_CYAN}systemctl restart nginxforge${COLOR_RESET}"
echo -e "  • View Logs:  ${COLOR_CYAN}journalctl -u nginxforge -f${COLOR_RESET}\n"
