#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
export LC_ALL=C
export DEBIAN_FRONTEND=noninteractive
export NEEDRESTART_MODE=l

usage() {
  cat <<'USAGE'
D54 HostPanel v1.0.0 Kurulum Betiği (Ubuntu 24.04 / 22.04 · Debian 12)

Kullanım:
  sudo bash d54-hostpanel-install.sh --domain panel.alanadiniz.com \
    --mail-host mail.alanadiniz.com --email admin@alanadiniz.com \
    (--license D54HP-XXXX-XXXX | --trial) \
    [--ssh-port 22] [--php-versions 8.2,8.3,8.4] [--bundle-url URL]

Seçenekler:
  --domain FQDN         Panel ve mağaza alan adı (DNS bu sunucuya dönük olmalı)
  --mail-host FQDN      Ana posta sunucusu FQDN (örn. mail.alanadiniz.com)
  --email ADRES         Let's Encrypt bildirim e-postası
  --license ANAHTAR     ElitHost üzerinden satın alınan D54 HostPanel lisansı
  --trial               15 günlük ücretsiz tam özellikli deneme lisansı ile kur
  --ssh-port PORT       Mevcut/hedef SSH portu (varsayılan: mevcut sshd portu)
  --php-versions LISTE  Kurulacak PHP sürümleri (varsayılan: 8.2,8.3,8.4)
  --bundle-url URL      Özel arşiv URL'i (varsayılan: PatikaHub CDN)
USAGE
}

die() { printf 'D54 HostPanel Kurulum Hatası: %s\n' "$*" >&2; exit 1; }
say() { printf 'D54 HostPanel: %s\n' "$*"; }

DEFAULT_BUNDLE_URL="https://patikahub.com/elithost/d54-hostpanel-v1.0.0-linux-amd64.tar.gz"

domain=""
mail_host=""
acme_email=""
license_key=""
trial_mode=false
ssh_port=""
php_versions="8.2,8.3,8.4"
bundle_url="$DEFAULT_BUNDLE_URL"

while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0 ;;
    --trial) trial_mode=true; shift ;;
    --domain|--mail-host|--email|--license|--ssh-port|--php-versions|--bundle-url)
      if (( $# < 2 )) || [[ -z $2 || $2 == --* ]]; then
        die "$1 bir değer gerektirir."
      fi
      case $1 in
        --domain) domain=${2,,} ;;
        --mail-host) mail_host=${2,,} ;;
        --email) acme_email=$2 ;;
        --license) license_key=$2 ;;
        --ssh-port) ssh_port=$2 ;;
        --php-versions) php_versions=$2 ;;
        --bundle-url) bundle_url=$2 ;;
      esac
      shift 2 ;;
    *) die "Bilinmeyen seçenek: $1" ;;
  esac
done

[[ $EUID -eq 0 ]] || die "Kurulum root (sudo) olarak çalıştırılmalıdır."
[[ -d /run/systemd/system ]] || die "systemd aktif olmalıdır."
[[ $(uname -m) == "x86_64" ]] || die "Yalnızca x86_64 (amd64) mimarisi desteklenir."

# shellcheck source=/etc/os-release
source /etc/os-release
case "${ID:-}:${VERSION_ID:-}" in
  ubuntu:24.04|ubuntu:22.04|debian:12) ;;
  *) die "Ubuntu 24.04, Ubuntu 22.04 veya Debian 12 gereklidir (tespit: ${ID:-?}:${VERSION_ID:-?})." ;;
esac

if [[ -z $domain || -z $mail_host || -z $acme_email ]]; then
  usage >&2
  exit 2
fi
if "$trial_mode" && [[ -n $license_key ]]; then
  die "--trial ve --license birlikte kullanılamaz."
fi
if "$trial_mode"; then
  license_key="TRIAL"
fi
[[ -n $license_key ]] || die "ElitHost lisans anahtarı (--license) veya 15 günlük deneme (--trial) seçilmelidir."

if [[ -z $ssh_port ]]; then
  ssh_port=$(sshd -T 2>/dev/null | awk '/^port /{print $2; exit}' || true)
  ssh_port=${ssh_port:-22}
fi

workdir=$(mktemp -d /run/d54-hostpanel-setup.XXXXXXXX)
cleanup() { rm -rf -- "$workdir"; }
trap cleanup EXIT

say "Temel sistem araçları ve veritabanı paketleri kuruluyor..."
apt-get -o APT::Update::Error-Mode=any update -qq
apt-get install -y -qq ca-certificates curl gnupg openssl python3 jq tar gzip \
  postgresql postgresql-contrib redis-server nginx certbot

if ! command -v node >/dev/null 2>&1 || [[ $(node -v | sed -E 's/^v([0-9]+).*/\1/') -lt 20 ]]; then
  say "Node.js 20 LTS kuruluyor..."
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash - >/dev/null
  apt-get install -y -qq nodejs
fi

bundle_tgz="$workdir/bundle.tar.gz"
bundle_sha="$workdir/bundle.tar.gz.sha256"
say "D54 HostPanel v1.0.0 sürüm arşivi indiriliyor..."
curl -fL --retry 3 --retry-delay 2 -o "$bundle_tgz" "$bundle_url"
curl -fL --retry 3 --retry-delay 2 -o "$bundle_sha" "${bundle_url}.sha256"

expected_sha=$(awk '{print $1}' "$bundle_sha")
actual_sha=$(sha256sum "$bundle_tgz" | awk '{print $1}')
[[ -n $expected_sha && $expected_sha == "$actual_sha" ]] || die "Arşiv SHA-256 doğrulaması başarısız!"
say "SHA-256 doğrulaması başarılı: $actual_sha"

extract_dir="$workdir/src"
mkdir -p "$extract_dir"
tar -xzf "$bundle_tgz" -C "$extract_dir"

[[ -x "$extract_dir/bin/d54-hostpanel-core" ]] || die "Arşiv içinde Core ikili dosyası eksik."
[[ -x "$extract_dir/bin/d54-hostpanel-daemon" ]] || die "Arşiv içinde Daemon ikili dosyası eksik."
[[ -f "$extract_dir/deploy/install-node.sh" ]] || die "Arşiv içinde düğüm kurulum betiği eksik."

say "Çevrimdışı mTLS PKI sertifikaları üretiliyor..."
pki_dir="/etc/d54-hostpanel/pki-setup"
install -d -m 0700 "$pki_dir/ca" "$pki_dir/core" "$pki_dir/daemon"
openssl genrsa -out "$pki_dir/ca/ca.key" 4096 2>/dev/null
openssl req -x509 -new -nodes -key "$pki_dir/ca/ca.key" -sha256 -days 3650 \
  -subj "/CN=D54 HostPanel Root CA" -out "$pki_dir/ca/ca.crt"

# Daemon server cert (127.0.0.1 SAN)
openssl genrsa -out "$pki_dir/daemon/server.key" 2048 2>/dev/null
cat > "$workdir/daemon-ext.cnf" <<'EOF'
subjectAltName = IP:127.0.0.1,DNS:localhost
extendedKeyUsage = serverAuth
EOF
openssl req -new -key "$pki_dir/daemon/server.key" -subj "/CN=d54-node-1" -out "$workdir/daemon.csr"
openssl x509 -req -in "$workdir/daemon.csr" -CA "$pki_dir/ca/ca.crt" -CAkey "$pki_dir/ca/ca.key" \
  -CAcreateserial -out "$pki_dir/daemon/server.crt" -days 1825 -sha256 -extfile "$workdir/daemon-ext.cnf"

# Core client cert
openssl genrsa -out "$pki_dir/core/client.key" 2048 2>/dev/null
cat > "$workdir/core-ext.cnf" <<'EOF'
extendedKeyUsage = clientAuth
EOF
openssl req -new -key "$pki_dir/core/client.key" -subj "/CN=d54-hostpanel-core" -out "$workdir/core.csr"
openssl x509 -req -in "$workdir/core.csr" -CA "$pki_dir/ca/ca.crt" -CAkey "$pki_dir/ca/ca.key" \
  -CAcreateserial -out "$pki_dir/core/client.crt" -days 1825 -sha256 -extfile "$workdir/core-ext.cnf"

say "Linux hosting düğümü kuruluyor (Nginx, PHP $php_versions, MariaDB, Postfix/Dovecot, PowerDNS, Rspamd/ClamAV)..."
bash "$extract_dir/deploy/install-node.sh" \
  --pki "$pki_dir" \
  --binary "$extract_dir/bin/d54-hostpanel-daemon" \
  --core-ip 127.0.0.1 \
  --node-id node1 \
  --mail-host "$mail_host" \
  --acme-email "$acme_email" \
  --ssh-port "$ssh_port" \
  --php-versions "$php_versions"

getent group d54hostpanel >/dev/null || groupadd --system d54hostpanel
if ! getent passwd d54hostpanel >/dev/null; then
  useradd --system --gid d54hostpanel --home-dir /opt/d54-hostpanel --shell /usr/sbin/nologin --no-create-home d54hostpanel
fi

install -d -m 0750 -o root -g d54hostpanel /etc/d54-hostpanel/core-certs
install -m 0640 -o root -g d54hostpanel "$pki_dir/ca/ca.crt" /etc/d54-hostpanel/core-certs/ca.crt
install -m 0640 -o root -g d54hostpanel "$pki_dir/core/client.crt" /etc/d54-hostpanel/core-certs/client.crt
install -m 0640 -o root -g d54hostpanel "$pki_dir/core/client.key" /etc/d54-hostpanel/core-certs/client.key
rm -rf -- "$pki_dir"

say "PostgreSQL 16 ve Redis 7 yapılandırılıyor..."
pg_pass=$(openssl rand -hex 24)
su - postgres -c "psql -tAc \"SELECT 1 FROM pg_roles WHERE rolname='d54hostpanel'\" | grep -q 1 || psql -c \"CREATE USER d54hostpanel WITH PASSWORD '$pg_pass';\""
su - postgres -c "psql -tAc \"SELECT 1 FROM pg_database WHERE datname='d54hostpanel'\" | grep -q 1 || psql -c \"CREATE DATABASE d54hostpanel OWNER d54hostpanel;\""
su - postgres -c "psql -c \"ALTER USER d54hostpanel WITH PASSWORD '$pg_pass';\"" >/dev/null
systemctl enable --now postgresql.service redis-server.service

admin_token=$(openssl rand -hex 32)
jwt_seed=$(openssl rand -base64 32)
totp_key=$(openssl rand -base64 32)
ui_session_key=$(openssl rand -hex 32)

install -d -m 0755 /opt/d54-hostpanel/bin /opt/d54-hostpanel/ui
install -m 0755 "$extract_dir/bin/d54-hostpanel-core" /opt/d54-hostpanel/bin/d54-hostpanel-core
rm -rf /opt/d54-hostpanel/ui
cp -a "$extract_dir/ui" /opt/d54-hostpanel/ui
mkdir -p /opt/d54-hostpanel/ui/.next/cache
chown -R d54hostpanel:d54hostpanel /opt/d54-hostpanel/ui/.next/cache
chmod -R a+rX /opt/d54-hostpanel/ui

cat > /etc/d54-hostpanel/core.env <<ENV
D54_HTTP_ADDR=127.0.0.1:8080
D54_DATABASE_URL=postgres://d54hostpanel:${pg_pass}@127.0.0.1:5432/d54hostpanel?sslmode=disable
D54_REDIS_URL=redis://127.0.0.1:6379/0
D54_CORE_PKI_DIR=/etc/d54-hostpanel/core-certs
D54_MACHINE_ID_FILE=/etc/machine-id
D54_PUBLIC_URL=https://${domain}
D54_CHECKOUT_RETURN_URL=https://${domain}/odeme-sonucu
D54_TRUSTED_PROXIES=127.0.0.1,::1
D54_ADMIN_TOKEN=${admin_token}
D54_JWT_SEED=${jwt_seed}
D54_TOTP_KEY=${totp_key}
D54_LICENSE_KEY=${license_key}
D54_PAYTR_MERCHANT_ID=demo-configure-in-admin
D54_PAYTR_KEY=demo-configure-in-admin
D54_PAYTR_SALT=demo-configure-in-admin
D54_PAYTR_TEST=true
D54_IYZICO_ORIGIN=https://sandbox-api.iyzipay.com
D54_IYZICO_API_KEY=demo-configure-in-admin
D54_IYZICO_SECRET=demo-configure-in-admin
D54_EARCHIVE_URL=https://earchive.invalid/api/v1/issue
D54_EARCHIVE_TOKEN=demo-configure-in-admin
ENV
chown root:d54hostpanel /etc/d54-hostpanel/core.env
chmod 0640 /etc/d54-hostpanel/core.env

cat > /etc/d54-hostpanel/ui.env <<ENV
D54_CORE_URL=http://127.0.0.1:8080
D54_UI_ADMIN_TOKEN=${admin_token}
D54_UI_ORIGIN=https://${domain}
D54_UI_SESSION_KEY=${ui_session_key}
D54_UI_TRUST_PROXY=true
D54_WEBMAIL_URL=https://${mail_host}/
HOSTNAME=127.0.0.1
NEXT_TELEMETRY_DISABLED=1
NODE_ENV=production
PORT=3000
ENV
chown root:d54hostpanel /etc/d54-hostpanel/ui.env
chmod 0640 /etc/d54-hostpanel/ui.env

cat > /etc/systemd/system/d54-hostpanel-core.service <<'UNIT'
[Unit]
Description=D54 HostPanel Core API & Worker
After=network-online.target postgresql.service redis-server.service
Wants=network-online.target

[Service]
Type=simple
User=d54hostpanel
Group=d54hostpanel
EnvironmentFile=/etc/d54-hostpanel/core.env
ExecStart=/opt/d54-hostpanel/bin/d54-hostpanel-core
Restart=on-failure
RestartSec=5s
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes

[Install]
WantedBy=multi-user.target
UNIT

cat > /etc/systemd/system/d54-hostpanel-ui.service <<'UNIT'
[Unit]
Description=D54 HostPanel Next.js UI
After=network-online.target d54-hostpanel-core.service
Wants=network-online.target

[Service]
Type=simple
User=d54hostpanel
Group=d54hostpanel
WorkingDirectory=/opt/d54-hostpanel/ui
EnvironmentFile=/etc/d54-hostpanel/ui.env
ExecStart=/usr/bin/node /opt/d54-hostpanel/ui/server.js
Restart=on-failure
RestartSec=5s
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/d54-hostpanel/ui/.next/cache

[Install]
WantedBy=multi-user.target
UNIT

say "Panel Nginx vhost ve SSL sertifikası hazırlanıyor..."
install -d -m 0755 /var/www/d54-hostpanel-acme
cat > /etc/nginx/conf.d/d54-hostpanel-panel.conf <<NGINX
server {
  listen 80;
  listen [::]:80;
  server_name ${domain};
  location ^~ /.well-known/acme-challenge/ { root /var/www/d54-hostpanel-acme; }
  location / { return 301 https://\$host\$request_uri; }
}
NGINX
nginx -t && systemctl reload nginx.service

if certbot certonly --non-interactive --agree-tos --keep-until-expiring \
  --email "$acme_email" --cert-name d54-hostpanel-panel \
  --webroot --webroot-path /var/www/d54-hostpanel-acme -d "$domain"; then
  cat > /etc/nginx/conf.d/d54-hostpanel-panel.conf <<NGINX
server {
  listen 80;
  listen [::]:80;
  server_name ${domain};
  location ^~ /.well-known/acme-challenge/ { root /var/www/d54-hostpanel-acme; }
  location / { return 301 https://\$host\$request_uri; }
}

server {
  listen 443 ssl;
  listen [::]:443 ssl;
  http2 on;
  server_name ${domain};

  ssl_certificate /etc/letsencrypt/live/d54-hostpanel-panel/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/d54-hostpanel-panel/privkey.pem;

  add_header Strict-Transport-Security "max-age=31536000" always;
  add_header X-Content-Type-Options "nosniff" always;
  add_header Referrer-Policy "strict-origin-when-cross-origin" always;
  add_header X-Frame-Options "DENY" always;

  location ^~ /api/actions/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
  }

  location /api/v1/ {
    return 404;
  }

  location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Host \$host;
    proxy_set_header X-Real-IP \$remote_addr;
    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
  }
}
NGINX
  nginx -t && systemctl reload nginx.service
else
  say "UYARI: ${domain} için Let's Encrypt sertifikası alınamadı (DNS henüz bu sunucuya dönmemiş olabilir)."
fi

systemctl daemon-reload
systemctl enable --now d54-hostpanel-core.service d54-hostpanel-ui.service

for _ in $(seq 1 20); do
  if curl -fsS -o /dev/null http://127.0.0.1:8080/healthz; then
    break
  fi
  sleep 1
done

curl -fsS -o /dev/null http://127.0.0.1:8080/healthz || die "Core API sağlık kontrolü başarısız!"
say "D54 HostPanel kurulumu tamamlandı."
printf '\n==========================================================\n'
printf 'Panel Adresi       : https://%s/yonetim-giris\n' "$domain"
printf 'Webmail Adresi     : https://%s/\n' "$mail_host"
printf 'Yonetim Anahtari   : %s\n' "$admin_token"
printf 'Lisans Modu        : %s\n' "$license_key"
printf '==========================================================\n'
printf 'NOT: Yukaridaki Yonetim Anahtarini guvenli bir yerde saklayiniz.\n'
