#!/bin/bash
# TriPanel One-Line Installer - AlmaLinux 9/10
# Usage: curl -fsSL https://download.tripanel.net/install.sh | bash
#        curl -fsSL https://download.tripanel.net/install.sh | bash -s -- --profile minimal  # 1GB (1.3GB cap)
#        curl -fsSL https://download.tripanel.net/install.sh | bash -s -- --profile standard # 1.5GB
#        curl -fsSL https://download.tripanel.net/install.sh | bash -s -- --profile balanced # 2GB
#        curl -fsSL https://download.tripanel.net/install.sh | bash -s -- --profile performance # 2.5GB max
# Or: bash install.sh --uninstall / --update / --profile <name>
set -e
TRIPANEL_VERSION="1.0.0"
INSTALL_DIR="/root/panel"
LOG="/var/log/tripanel-install.log"

# Colors
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'

log() { echo -e "${GREEN}[TriPanel]${NC} $1" | tee -a "$LOG"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1" | tee -a "$LOG"; }
err() { echo -e "${RED}[ERR]${NC} $1" | tee -a "$LOG"; exit 1; }

PROFILE="auto"
for arg in "$@"; do case $arg in --profile=*) PROFILE="${arg#*=}";; --profile) shift; PROFILE="$1";; esac; done
# Normalize profile names
case "$PROFILE" in minimal|1gb|1.3gb) PROFILE="minimal";; standard|1.5gb) PROFILE="standard";; balanced|2gb) PROFILE="balanced";; performance|2.5gb|max) PROFILE="performance";; auto) ;; esac

preflight() {
  log "Preflight check (profile: $PROFILE)..."
  # OS
  if ! grep -q "AlmaLinux" /etc/os-release 2>/dev/null; then
    warn "Not AlmaLinux - trying anyway"
  fi
  # RAM — profiles: minimal 1GB (1.3GB cap like cPanel), standard 1.5GB, balanced 2GB, performance 2.5GB max
  RAM=$(free -m | awk '/^Mem:/{print $2}')
  case "$PROFILE" in
    minimal) [ "$RAM" -lt 900 ] && warn "RAM ${RAM}MB < 1GB for minimal" ;;
    standard) [ "$RAM" -lt 1300 ] && warn "RAM ${RAM}MB < 1.5GB for standard" ;;
    balanced) [ "$RAM" -lt 1800 ] && warn "RAM ${RAM}MB < 2GB for balanced" ;;
    performance) [ "$RAM" -lt 2300 ] && warn "RAM ${RAM}MB < 2.5GB for performance" ;;
    *) [ "$RAM" -lt 1800 ] && warn "RAM ${RAM}MB < 2GB recommended" ;;
  esac
  # Disk
  DISK=$(df -BG / | awk 'NR==2{print $4}' | tr -d 'G')
  [ "$DISK" -lt 15 ] && err "Disk < 15GB free"
  # Ports
  for p in 80 443 2083 2087 2096 25 587 993; do
    ss -tulpn 2>/dev/null | grep -q ":$p " && warn "Port $p already in use"
  done
  # Root
  [ "$EUID" -ne 0 ] && err "Run as root"
  log "Preflight OK (Alma $(cat /etc/almalinux-release 2>/dev/null || cat /etc/os-release | grep PRETTY_NAME) RAM ${RAM}MB Disk ${DISK}GB)"
}

install_deps() {
  log "Installing dependencies..."
  dnf -y install epel-release 2>&1 | tail -1
  dnf -y install nginx pdns pdns-backend-mysql mariadb-server php-fpm php-cli php-mysqlnd certbot python3-certbot-nginx rspamd opendkim redis memcached fail2ban netdata go nodejs npm awscli rclone 2>&1 | tail -5
  # Trimail
  if ! systemctl list-unit-files | grep -q trimail; then
    log "Installing Trimail (Go SMTP)..."
    # Already built in repo - just ensure service exists
    systemctl enable trimail-mta trimail-edge 2>&1 | head -2
  fi
  log "Deps installed"
}

install_panel() {
  log "Installing TriPanel $TRIPANEL_VERSION to $INSTALL_DIR..."
  mkdir -p "$INSTALL_DIR"
  # Backend
  cd "$INSTALL_DIR/backend-go"
  go build -o tripanel-server . 2>&1 | tail -3
  # Frontend
  cd "$INSTALL_DIR/frontend"
  npm ci 2>&1 | tail -3
  npm run build 2>&1 | tail -3
  npm run deploy 2>&1 | tail -3
  # Systemd
  cat > /etc/systemd/system/tripanel-go.service <<'EOF'
[Unit]
Description=TriPanel Go Backend
After=network.target mariadb.service
[Service]
WorkingDirectory=/root/panel/backend-go
ExecStartPre=/usr/sbin/restorecon -F /root/panel/backend-go/tripanel-server
ExecStart=/root/panel/backend-go/tripanel-server
Restart=always
[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable --now tripanel-go mariadb nginx pdns php-fpm fail2ban 2>&1 | tail -3
  # Certbot renew timer (like cPanel AutoSSL daily)
  cat > /etc/systemd/system/certbot-renew.service <<'EOF'
[Unit]
Description=Certbot Renew (TriPanel AutoSSL)
[Service]
Type=oneshot
ExecStart=/usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx"
EOF
  cat > /etc/systemd/system/certbot-renew.timer <<'EOF'
[Unit]
Description=Daily Certbot Renew
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
EOF
  systemctl daemon-reload
  systemctl enable --now certbot-renew.timer 2>&1 | tail -2
  # Backup cron (WHM → Backup Configuration daily)
  (crontab -l 2>/dev/null; echo "30 3 * * * /usr/local/bin/tripanel-backup.sh") | crontab - 2>&1 | head -2
  log "Panel installed - https://$(hostname -f):2087 (admin) :2083 (user) :2096 (owner)"
}

uninstall() {
  warn "Uninstalling TriPanel..."
  systemctl disable --now tripanel-go 2>&1 | head -2
  rm -f /etc/systemd/system/tripanel-go.service /etc/systemd/system/certbot-renew.*
  systemctl daemon-reload
  warn "DB and homes preserved at /var/lib/mysql and /home - remove manually if needed"
  log "Uninstalled"
  exit 0
}

update() {
  log "Updating TriPanel..."
  cd "$INSTALL_DIR" && git pull 2>&1 | tail -3
  install_panel
  log "Updated to $(cat $INSTALL_DIR/VERSION 2>/dev/null || echo $TRIPANEL_VERSION)"
  exit 0
}

case "$1" in
  --uninstall) uninstall ;;
  --update) update ;;
  --preflight) preflight; exit 0 ;;
  --profile|--profile=*) ;; # handled above
esac

preflight
install_deps
install_panel
# Apply RAM profile optimization (like WHM → Service Manager → Low RAM)
if [ -x /usr/local/bin/tripanel-optimize-ram.sh ]; then
  log "Applying RAM profile: $PROFILE (max 2.5GB cap)"
  /usr/local/bin/tripanel-optimize-ram.sh "$PROFILE" 2>&1 | tail -5
fi
log "Done! Login: https://$(hostname -f):2087 admin / your password (profile: $PROFILE)"
log "Docs: https://tripanel.net/docs  Support: https://tripanel.net/support"
log "WHMCS module: /root/panel/modules/whmcs/tripanel/"
log "Switch profile later: tripanel-optimize-ram.sh [minimal|standard|balanced|performance] or WHM → Technologies"
