#!/bin/bash
# ══════════════════════════════════════════════════════════════════════════════
# NexioCP Panel — Sunucu Kurulum Scripti
# Hedef  : Ubuntu 22.04 / 24.04 LTS  (x86-64 veya ARM64)
# Kullanım: wget https://cdn.nexiocp.com/install.sh && chmod +x install.sh && sudo ./install.sh
# ══════════════════════════════════════════════════════════════════════════════
set -euo pipefail

# ── Sürüm & CDN ───────────────────────────────────────────────────────────────
NEXIOCP_VERSION="${NEXIOCP_VERSION:-1.0.6}"
CDN_BASE="${CDN_BASE:-https://cdn.nexiocp.com}"

# ── Dizinler & Portlar ────────────────────────────────────────────────────────
PANEL_DIR="/opt/nexiocp"
DATA_DIR="/var/lib/nexiocp"
LOG_DIR="/var/log/nexiocp"
BACKUP_DIR="/var/backups/nexiocp"
WEBROOT="/var/www"
CONFIG_DIR="/etc/nexiocp"
PANEL_PORT=7810
PANEL_PUBLIC_PORT=80          # nginx dış portu
PANEL_SSL_PORT=8443           # Panel SSL portu (Cloudflare uyumlu)

# ── Çevreden değer alınabilir ─────────────────────────────────────────────────
MYSQL_ROOT_PASS="${MYSQL_ROOT_PASS:-}"
ACME_EMAIL="${ACME_EMAIL:-}"
PANEL_DOMAIN="${PANEL_DOMAIN:-}"   # Panel SSL domaini (örn: panel.gezirota.com)

# ── Renkler & yardımcılar ─────────────────────────────────────────────────────
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;36m'
CYAN='\033[1;97m'
WHITE='\033[1;97m'
MAGENTA='\033[1;35m'
BOLD='\033[1m'
NC='\033[0m'

ok()   { echo -e "${GREEN}[✓]${NC} $*"; }
info() { echo -e "${CYAN}[→]${NC} $*"; }
warn() { echo -e "${YELLOW}[!]${NC} $*"; }
die()  { echo -e "${RED}[✗]${NC} $*" >&2; exit 1; }
step() { echo -e "\n${BOLD}${BLUE}━━━━  $*  ━━━━${NC}\n"; }

# ── Banner ────────────────────────────────────────────────────────────────────
clear
echo -e "${BLUE}${BOLD}"
cat << 'BANNER'
  _   _           _        ____  ____
 | \ | | _____  _(_) ___  / ___|  _ \
 |  \| |/ _ \ \/ / |/ _ \| |   | |_) |
 | |\  |  __/>  <| | (_) | |___|  __/
 |_| \_|\___/_/\_\_|\___/ \____|_|

BANNER
echo -e "${NC}${BOLD}  Hosting Control Panel  —  Kurulum v${NEXIOCP_VERSION}${NC}"
echo -e "  ${CYAN}https://nexiocp.com${NC}"
echo ""

# ═══════════════════════════════════════════════════════════════════════════════
step "Ön Kontroller"
# ═══════════════════════════════════════════════════════════════════════════════
[[ $EUID -ne 0 ]] && die "Bu scripti root olarak çalıştırın: sudo bash install.sh"

# İşletim sistemi kontrolü
if [[ -f /etc/os-release ]]; then
    . /etc/os-release
    if [[ "$ID" != "ubuntu" ]]; then
        die "Sadece Ubuntu desteklenmektedir. Mevcut: ${PRETTY_NAME:-bilinmiyor}"
    fi
    UBUNTU_VER="${VERSION_ID:-0}"
    if [[ "$UBUNTU_VER" != "22.04" && "$UBUNTU_VER" != "24.04" ]]; then
        warn "Test edilen sürümler: 22.04 / 24.04. Mevcut: $UBUNTU_VER — devam ediliyor..."
    fi
else
    die "/etc/os-release bulunamadı. Ubuntu 22.04+ gereklidir."
fi

# Mimari
ARCH=$(uname -m)
case "$ARCH" in
    x86_64)  ARCH_DL="amd64" ;;
    aarch64) ARCH_DL="arm64" ;;
    *) die "Desteklenmeyen mimari: $ARCH (sadece x86_64 / aarch64)" ;;
esac

# RAM kontrolü (minimum 512 MB)
TOTAL_RAM_MB=$(awk '/MemTotal/{print int($2/1024)}' /proc/meminfo)
if [[ $TOTAL_RAM_MB -lt 512 ]]; then
    die "Yetersiz RAM: ${TOTAL_RAM_MB}MB (minimum 512MB gerekli)"
fi

# Disk kontrolü — minimum 5 GB
FREE_GB=$(df -BG / | awk 'NR==2{gsub("G",""); print $4}')
if [[ $FREE_GB -lt 5 ]]; then
    die "Yetersiz disk alanı: ${FREE_GB}GB boş (minimum 5GB gerekli)"
fi

# Sunucu IP'sini tespit et
SERVER_IP=$(curl -s --max-time 5 ifconfig.me 2>/dev/null \
         || curl -s --max-time 5 api.ipify.org 2>/dev/null \
         || hostname -I | awk '{print $1}')

ok "Ubuntu ${UBUNTU_VER} (${ARCH}) — RAM: ${TOTAL_RAM_MB}MB — Disk: ${FREE_GB}GB boş"
ok "Sunucu IP: ${SERVER_IP}"

# ═══════════════════════════════════════════════════════════════════════════════
step "Sistem Ayarları"
# ═══════════════════════════════════════════════════════════════════════════════

# Timezone: Europe/Istanbul
if command -v timedatectl &>/dev/null; then
    timedatectl set-timezone Europe/Istanbul
    timedatectl set-ntp true
    ok "Timezone: Europe/Istanbul (+03)"
else
    ln -sf /usr/share/zoneinfo/Europe/Istanbul /etc/localtime
    ok "Timezone: Europe/Istanbul (+03) (symlink)"
fi

# ═══════════════════════════════════════════════════════════════════════════════
step "Sistem Güncelleme & Temel Paketler"
# ═══════════════════════════════════════════════════════════════════════════════
export DEBIAN_FRONTEND=noninteractive

apt-get update -qq
apt-get upgrade -y -qq
apt-get install -y -qq \
    curl wget git unzip openssl \
    build-essential gcc make \
    sqlite3 \
    ca-certificates gnupg lsb-release \
    software-properties-common \
    apt-transport-https \
    cron \
    logrotate \
    acl \
    zip unzip \
    pwgen \
    net-tools \
    dnsutils \
    htop \
    jq

ok "Temel paketler kuruldu"

# ═══════════════════════════════════════════════════════════════════════════════
step "Nginx"
# ═══════════════════════════════════════════════════════════════════════════════

apt-get install -y -qq nginx certbot python3-certbot-nginx
systemctl enable nginx
systemctl start nginx 2>/dev/null || true

# ── phpMyAdmin (non-interactive) ─────────────────────────────────────────────
echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect none" | debconf-set-selections 2>/dev/null || true
echo "phpmyadmin phpmyadmin/dbconfig-install boolean false"         | debconf-set-selections 2>/dev/null || true
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq phpmyadmin || warn "phpMyAdmin paketi kurulamadı, kurulum devam ediyor"

# Varsayılan siteyi kapat
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx 2>/dev/null || true

ok "Nginx kuruldu"

# ═══════════════════════════════════════════════════════════════════════════════
step "PHP 8.3 + FPM"
# ═══════════════════════════════════════════════════════════════════════════════
# Ondrej PPA — PHP 5.6/7.x/8.x tüm sürümler için gerekli.
# Panel üzerinden ek sürüm kurulabilmesi için PPA her zaman eklenir.
info "Ondrej PPA ekleniyor..."
if ! apt-cache show php8.3-fpm &>/dev/null 2>&1; then
    add-apt-repository -y ppa:ondrej/php
    apt-get update -qq
fi

# ── Varsayılan PHP sürümü: 8.3 ────────────────────────────────────────────────
# Diğer sürümler (5.6, 7.x, 8.0-8.2, 8.4) panel üzerinden kurulabilir:
# PHP Yönetimi → PHP Sürüm Yönetimi → İstediğiniz sürüm → Kur
DEFAULT_PHP="8.3"
PHP_MODS="fpm cli mysql curl mbstring xml zip gd intl bcmath soap opcache readline"

info "PHP ${DEFAULT_PHP} kuruluyor..."
apt-get install -y -qq php${DEFAULT_PHP}-fpm php${DEFAULT_PHP}-cli || \
    die "PHP ${DEFAULT_PHP} paketi kurulamadı"

for MOD in $PHP_MODS; do
    apt-get install -y -qq php${DEFAULT_PHP}-${MOD} 2>/dev/null || true
done

# FPM etkinleştir ve güvenlik ayarları
systemctl enable php${DEFAULT_PHP}-fpm
if [[ -f /etc/php/${DEFAULT_PHP}/fpm/php.ini ]]; then
    sed -i \
        -e 's/^expose_php\s*=.*/expose_php = Off/' \
        -e 's/^;cgi.fix_pathinfo\s*=.*/cgi.fix_pathinfo = 0/' \
        /etc/php/${DEFAULT_PHP}/fpm/php.ini 2>/dev/null || true
fi

ok "PHP ${DEFAULT_PHP} + FPM kuruldu"
info "Ek PHP sürümleri panelden kurulabilir: PHP Yönetimi → PHP Sürüm Yönetimi"

# ── Composer ──────────────────────────────────────────────────────────────────
info "Composer kuruluyor..."
curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php
php8.3 /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer --quiet < /dev/null
rm -f /tmp/composer-setup.php
chmod +x /usr/local/bin/composer
info "Lütfen Enter Tusuna Basınız...."
ok "Composer $(composer --version 2>/dev/null | awk '{print $3}') kuruldu → /usr/local/bin/composer"

# ═══════════════════════════════════════════════════════════════════════════════
step "MySQL"
# ═══════════════════════════════════════════════════════════════════════════════
if ! command -v mysqld &>/dev/null && ! command -v mariadbd &>/dev/null; then
    apt-get install -y -qq mysql-server
fi
systemctl enable mysql

# MySQL 8 default auth plugin — PHP 5.6/7.x/8.x tüm sürümlerle uyumlu olması için
MYSQLD_CNF="/etc/mysql/mysql.conf.d/mysqld.cnf"
if [ -f "${MYSQLD_CNF}" ] && ! grep -q "default_authentication_plugin" "${MYSQLD_CNF}"; then
    echo "" >> "${MYSQLD_CNF}"
    echo "default_authentication_plugin=mysql_native_password" >> "${MYSQLD_CNF}"
    systemctl restart mysql
    ok "MySQL default auth plugin: mysql_native_password"
fi

# Root şifresi
if [[ -z "$MYSQL_ROOT_PASS" ]]; then
    MYSQL_ROOT_PASS=$(openssl rand -base64 32 | tr -dc 'A-Za-z0-9' | head -c 24)
fi

MYSQL_PASS_FILE="${CONFIG_DIR}/mysql_root.passwd"
mkdir -p "$CONFIG_DIR"
echo "$MYSQL_ROOT_PASS" > "$MYSQL_PASS_FILE"
chmod 600 "$MYSQL_PASS_FILE"

# Root şifresini ayarla ve güvenliği sıkılaştır
mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${MYSQL_ROOT_PASS}';" 2>/dev/null \
    || mysql -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${MYSQL_ROOT_PASS}';" 2>/dev/null \
    || true

mysql -u root -p"${MYSQL_ROOT_PASS}" -e "
    DELETE FROM mysql.user WHERE User='';
    DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
    DROP DATABASE IF EXISTS test;
    DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
    FLUSH PRIVILEGES;
" 2>/dev/null || true

# .my.cnf oluştur (panel için root erişimi)
cat > /root/.my.cnf << EOF
[client]
user=root
password=${MYSQL_ROOT_PASS}
EOF
chmod 600 /root/.my.cnf

ok "MySQL kuruldu  (şifre: ${MYSQL_PASS_FILE})"

# ═══════════════════════════════════════════════════════════════════════════════
step "Postfix + Dovecot + OpenDKIM"
# ═══════════════════════════════════════════════════════════════════════════════
info "Postfix kuruluyor..."
echo "postfix postfix/mailname string ${SERVER_IP}"            | debconf-set-selections 2>/dev/null || true
echo "postfix postfix/main_mailer_type string 'Internet Site'" | debconf-set-selections 2>/dev/null || true

apt-get install -y -qq \
    postfix postfix-mysql \
    dovecot-core dovecot-imapd dovecot-pop3d dovecot-lmtpd dovecot-mysql \
    opendkim opendkim-tools

systemctl enable postfix dovecot opendkim
systemctl start postfix dovecot 2>/dev/null || true

# Postfix temel ayarları
postconf -e "inet_interfaces = all"
postconf -e "inet_protocols = ipv4"
postconf -e "smtpd_use_tls = yes"
postconf -e "smtpd_tls_security_level = may"
postconf -e "smtp_tls_security_level = may"
postconf -e "smtpd_banner = \$myhostname ESMTP"
postconf -e "smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination"
postconf -e "virtual_mailbox_base = /var/mail/vhosts"
postconf -e "message_size_limit = 52428800"

# Virtual mailbox dizini
mkdir -p /var/mail/vhosts
chmod 770 /var/mail/vhosts

# OpenDKIM temel ayar
mkdir -p /etc/opendkim/keys
cat > /etc/opendkim.conf << 'DKIM'
Syslog          yes
SyslogSuccess   yes
LogWhy          yes
Canonicalization relaxed/simple
Mode            sv
SubDomains      no
AutoRestart     yes
AutoRestartRate 10/1M
Background      yes
DNSTimeout      5
SignatureAlgorithm rsa-sha256
UMask           002
KeyTable        /etc/opendkim/KeyTable
SigningTable    refile:/etc/opendkim/SigningTable
ExternalIgnoreList /etc/opendkim/TrustedHosts
InternalHosts   /etc/opendkim/TrustedHosts
DKIM

cat > /etc/opendkim/TrustedHosts << 'EOF'
127.0.0.1
::1
localhost
EOF

touch /etc/opendkim/KeyTable
touch /etc/opendkim/SigningTable
chown -R opendkim:opendkim /etc/opendkim

# Postfix → OpenDKIM bağlantısı
postconf -e "milter_default_action = accept"
postconf -e "milter_protocol = 6"
postconf -e "smtpd_milters = local:opendkim/opendkim.sock"
postconf -e "non_smtpd_milters = \$smtpd_milters"

# Postfix SASL (Dovecot auth) + Submission port 587
postconf -e "smtpd_sasl_type=dovecot"
postconf -e "smtpd_sasl_path=private/auth"
postconf -e "smtpd_sasl_auth_enable=yes"
postconf -e "smtpd_sasl_security_options=noanonymous"

# master.cf — submission port 587 aç (chroot=n zorunlu, yoksa pid/inet.submission lock hatası)
sed -i 's|^#submission inet n|submission inet n|' /etc/postfix/master.cf
# chroot sütununu y→n yap (4. sütun): "submission inet n - y - - smtpd" → "submission inet n - n - - smtpd"
sed -i 's|^submission inet n\([ \t]*\)-\([ \t]*\)y\([ \t]*\)|submission inet n\1-\2n\3|' /etc/postfix/master.cf
sed -i '/^submission inet/,/^[a-z#]/{
    s|^#  -o syslog_name=postfix/submission|  -o syslog_name=postfix/submission|
    s|^#  -o smtpd_sasl_auth_enable=yes|  -o smtpd_sasl_auth_enable=yes|
}' /etc/postfix/master.cf

# Virtual mailbox dizini (vmail user'ı kurulumdan önce oluştur)
useradd -r -u 5000 -g 5000 -d /var/mail/vhosts -s /sbin/nologin vmail 2>/dev/null || true
mkdir -p /var/mail/vhosts
chown vmail:vmail /var/mail/vhosts
chmod 755 /var/mail/vhosts

# Dovecot: virtual user auth (passwdfile) + mail location + uid/gid
sed -i 's|^#!include auth-passwdfile.conf.ext|!include auth-passwdfile.conf.ext|' /etc/dovecot/conf.d/10-auth.conf

# Dovecot: sistem PAM auth'u kapat — sanal email kullanıcıları (user@domain.com)
# sistem kullanıcısı değil, PAM auth PLAIN bağlantıyı reddeder ve passwd-file'a geçmez
sed -i 's|^!include auth-system.conf.ext|#!include auth-system.conf.ext|' /etc/dovecot/conf.d/10-auth.conf

sed -i 's|^mail_location = mbox.*|mail_location = maildir:/var/mail/vhosts/%d/%n|' /etc/dovecot/conf.d/10-mail.conf
grep -q "^mail_uid" /etc/dovecot/conf.d/10-mail.conf || echo "mail_uid = vmail" >> /etc/dovecot/conf.d/10-mail.conf
grep -q "^mail_gid" /etc/dovecot/conf.d/10-mail.conf || echo "mail_gid = vmail" >> /etc/dovecot/conf.d/10-mail.conf

# Dovecot: Postfix SASL auth socket — 10-master.conf düzelt
# Ubuntu varsayılanında bu blok ya tamamen comment'li (#unix_listener) ya da kapanış brace'i
# comment'li (#}) gelir. İki durumu da regex ile yakala ve doğru blokla değiştir.
python3 - << 'MASTERFIX'
import re
path = '/etc/dovecot/conf.d/10-master.conf'
content = open(path).read()

# Hedef blok
new_block = '  unix_listener /var/spool/postfix/private/auth {\n    mode = 0666\n    user = postfix\n    group = postfix\n  }'

# Zaten düzeltilmişse atla
if 'mode = 0666' in content and 'user = postfix' in content:
    print('10-master.conf: zaten duzeltilmis, atlandi')
else:
    # Tüm varyantları yakala: satır başındaki # opsiyonel, içerik opsiyonel comment
    pattern = r'#?\s*unix_listener\s+/var/spool/postfix/private/auth\s*\{[^}]*\}'
    new_content, n = re.subn(pattern, new_block, content, flags=re.DOTALL)
    if n > 0:
        open(path, 'w').write(new_content)
        print(f'10-master.conf: {n} degisiklik yapildi')
    else:
        # Hiç yoksa service auth bloğunun sonuna ekle
        new_content = re.sub(
            r'(service auth \{[^}]*)(})',
            lambda m: m.group(1) + new_block + '\n' + m.group(2),
            content, flags=re.DOTALL
        )
        open(path, 'w').write(new_content)
        print('10-master.conf: blok eklendi')
MASTERFIX

# Config değişiklikleri uygulandı — servisleri yeniden başlat
# Dovecot önce: /var/spool/postfix/private/auth socket'ini oluştursun
# Postfix sonra: yeni SASL config + Dovecot socket'i ile başlasın
systemctl restart dovecot
sleep 2
systemctl restart postfix
sleep 1

ok "Postfix + Dovecot + OpenDKIM kuruldu"

# ═══════════════════════════════════════════════════════════════════════════════
step "Roundcube Webmail + Dovecot Master User (SSO)"
# ═══════════════════════════════════════════════════════════════════════════════
info "Roundcube kuruluyor..."

# Roundcube DB şifresi üret
ROUNDCUBE_DB_PASS=$(openssl rand -hex 16)

# debconf olmadan kur — DB'yi sonra manuel yapılandırıyoruz
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq roundcube roundcube-core roundcube-mysql \
    || warn "Roundcube kurulamadı — webmail SSO çalışmayabilir"

# MySQL DB ve kullanıcı oluştur
mysql -u root -p"${MYSQL_ROOT_PASS}" 2>/dev/null <<SQL || true
CREATE DATABASE IF NOT EXISTS roundcubemail CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'roundcube'@'localhost' IDENTIFIED BY '${ROUNDCUBE_DB_PASS}';
ALTER USER 'roundcube'@'localhost' IDENTIFIED WITH mysql_native_password BY '${ROUNDCUBE_DB_PASS}';
GRANT ALL PRIVILEGES ON roundcubemail.* TO 'roundcube'@'localhost';
FLUSH PRIVILEGES;
SQL

# Şema yoksa yükle
if ! mysql -u roundcube -p"${ROUNDCUBE_DB_PASS}" roundcubemail -e "SHOW TABLES;" 2>/dev/null | grep -q "users"; then
    mysql -u root -p"${MYSQL_ROOT_PASS}" roundcubemail < /usr/share/roundcube/SQL/mysql.initial.sql 2>/dev/null || true
fi

# debian-db.php: debconf'u bypass et, MySQL bağlantısını doğrudan yaz
cat > /etc/roundcube/debian-db.php << DBEOF
<?php
\$dbtype = 'mysql';
\$dbserver = 'localhost';
\$dbport = '';
\$dbname = 'roundcubemail';
\$dbuser = 'roundcube';
\$dbpass = '${ROUNDCUBE_DB_PASS}';
\$basepath = '';
\$dbcharset = 'utf8mb4';
\$dbcollation = 'utf8mb4_unicode_ci';
\$dbprefix = '';
DBEOF
chmod 640 /etc/roundcube/debian-db.php
chown root:www-data /etc/roundcube/debian-db.php
ok "Roundcube MySQL DB yapılandırıldı"

# ── Dovecot Master User ─────────────────────────────────────────────────────
WEBMAIL_MASTER_PASS=$(openssl rand -hex 24)

echo "nexiocp-master:{PLAIN}${WEBMAIL_MASTER_PASS}" > /etc/dovecot/master-users
chown root:dovecot /etc/dovecot/master-users
chmod 640 /etc/dovecot/master-users

# auth_master_user_separator — yorum satırını uncomment et
sed -i 's|^#auth_master_user_separator =.*|auth_master_user_separator = *|' /etc/dovecot/conf.d/10-auth.conf

# auth-master.conf.ext include'u aktif et (master user için)
sed -i 's|^#!include auth-master.conf.ext|!include auth-master.conf.ext|' /etc/dovecot/conf.d/10-auth.conf

# auth-master.conf.ext içindeki pass = yes satırını kaldır (virtual user ile uyumsuz)
sed -i '/pass = yes/d' /etc/dovecot/conf.d/auth-master.conf.ext

# Master password'u ve MySQL root şifresini NexioCP config dizinine kaydet
mkdir -p /etc/nexiocp
echo "${WEBMAIL_MASTER_PASS}" > /etc/nexiocp/webmail_master.passwd
chmod 600 /etc/nexiocp/webmail_master.passwd
if [[ -n "${MYSQL_ROOT_PASS}" ]]; then
    echo "${MYSQL_ROOT_PASS}" > /etc/nexiocp/mysql_root.passwd
    chmod 600 /etc/nexiocp/mysql_root.passwd
fi

systemctl reload dovecot 2>/dev/null || true

# ── Roundcube Yapılandırması ────────────────────────────────────────────────
ROUNDCUBE_CONF="/etc/roundcube/config.inc.php"

if [[ -f "${ROUNDCUBE_CONF}" ]]; then
    # NexioCP ayarlarını ekle (idempotent — sadece bir kez)
    if ! grep -q "nexiocp_sso" "${ROUNDCUBE_CONF}"; then
        cat >> "${ROUNDCUBE_CONF}" << 'RCEOF'

// NexioCP SSO Yapılandırması
$config['default_host']        = 'localhost';
$config['smtp_server']         = 'localhost';
$config['smtp_port']           = 587;
$config['smtp_user']           = '%u';
$config['smtp_pass']           = '%p';
$config['enable_csrf_token']   = false;
$config['plugins'] = array_unique(array_merge(
    isset($config['plugins']) ? $config['plugins'] : [],
    ['nexiocp_sso']
));
RCEOF
    fi

    # ── NexioCP SSO Plugin ─────────────────────────────────────────────────
    PLUGIN_DIR="/usr/share/roundcube/plugins/nexiocp_sso"
    mkdir -p "${PLUGIN_DIR}"

    cat > "${PLUGIN_DIR}/nexiocp_sso.php" << 'PLUGEOF'
<?php
/**
 * NexioCP SSO Plugin — Roundcube token tabanlı otomatik giriş
 */
class nexiocp_sso extends rcube_plugin {
    public $task = '.*';

    public function init() {
        $this->add_hook('startup', [$this, 'startup']);
    }

    public function startup($args) {
        $rcmail = rcmail::get_instance();

        // Token URL parametresini al ve temizle
        $token = isset($_GET['nexiocp_token'])
            ? preg_replace('/[^a-f0-9]/', '', $_GET['nexiocp_token'])
            : '';

        if (strlen($token) !== 32) return $args;

        $file = '/run/nexiocp/webmail-tokens/' . $token . '.json';
        if (!file_exists($file)) return $args;

        $data = json_decode(file_get_contents($file), true);
        @unlink($file); // Tek kullanımlık

        if (!$data || empty($data['username']) || empty($data['password'])) return $args;

        // Dovecot master user ile IMAP girişi
        $result = $rcmail->login($data['username'], $data['password'], 'localhost');
        if ($result) {
            $rcmail->session->regenerate_id(false);
            header('Location: /webmail/?_task=mail');
            exit;
        }

        return $args;
    }
}
PLUGEOF

    ok "Roundcube SSO plugin oluşturuldu: ${PLUGIN_DIR}/nexiocp_sso.php"
    ok "Roundcube webmail yapılandırıldı"

    # ── NexioCP Webmail Skin ───────────────────────────────────────────────────
    SKIN_SRC="/usr/share/roundcube/skins"
    NEXIO_SKIN="${SKIN_SRC}/nexiocp"
    RC_PUBSKINS="/var/lib/roundcube/public_html/skins"

    if [ -d "${SKIN_SRC}/elastic" ]; then
        info "NexioCP Roundcube skin oluşturuluyor..."
        cp -r "${SKIN_SRC}/elastic" "${NEXIO_SKIN}"

        # Logolar indir — sun: beyaz arka plan, dark: koyu arka plan
        mkdir -p "${NEXIO_SKIN}/images"
        LOGO_OK=0
        if curl -sf "${CDN_BASE}/logo-sun.png"  -o "${NEXIO_SKIN}/images/logo-sun.png"  2>/dev/null && \
           curl -sf "${CDN_BASE}/logo-dark.png" -o "${NEXIO_SKIN}/images/logo-dark.png" 2>/dev/null; then
            cp "${NEXIO_SKIN}/images/logo-sun.png" "${NEXIO_SKIN}/images/logo.png"
            ok "Logolar CDN'den indirildi (sun + dark)"
            LOGO_OK=1
        fi
        if [ "$LOGO_OK" -eq 0 ] && [ -f "/opt/nexiocp/logo-sun.png" ]; then
            cp "/opt/nexiocp/logo-sun.png"  "${NEXIO_SKIN}/images/logo-sun.png"
            cp "/opt/nexiocp/logo-sun.png"  "${NEXIO_SKIN}/images/logo.png"
            [ -f "/opt/nexiocp/logo-dark.png" ] && cp "/opt/nexiocp/logo-dark.png" "${NEXIO_SKIN}/images/logo-dark.png"
            LOGO_OK=1
        fi
        if [ "$LOGO_OK" -eq 0 ]; then
            cat > "${NEXIO_SKIN}/images/logo.svg" << 'SVGEOF'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 50">
  <text x="8" y="38" font-size="32" font-weight="bold" fill="#1e40af" font-family="Arial,sans-serif">NexioCP</text>
</svg>
SVGEOF
        fi

        # Özel login template
        mkdir -p "${NEXIO_SKIN}/templates"
        cat > "${NEXIO_SKIN}/templates/login.html" << 'LOGINEOF'
<roundcube:include file="includes/layout.html" />

<h1 class="voice"><roundcube:object name="productname" /> Webmail</h1>

<div id="layout-content" class="selected no-navbar" role="main">
  <div id="nexiocp-brand">
    <img src="skins/nexiocp/images/logo-sun.png" id="logo" alt="NexioCP"
         onerror="this.src='skins/nexiocp/images/logo.png'" />
    <h2>Webmail</h2>
    <p>E-posta hesabınıza giriş yapın</p>
  </div>

  <roundcube:form id="login-form" name="login-form" method="post" class="propform">
    <roundcube:object name="loginform" form="login-form" size="40" submit="true" class="form-control" />
    <div id="login-footer" role="contentinfo">
      <roundcube:object name="productname" condition="config:display_product_info &gt; 0" />
    </div>
  </roundcube:form>
</div>

<roundcube:include file="includes/footer.html" />
LOGINEOF

        # NexioCP CSS ekle
        mkdir -p "${NEXIO_SKIN}/styles"
        cat >> "${NEXIO_SKIN}/styles/styles.css" << 'CSSEOF'

/* ═══════════════════════════════════════════════
   NexioCP Webmail — Login Page Custom Branding
   ═══════════════════════════════════════════════ */

body.task-login {
    background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%) !important;
    min-height: 100vh;
}

body.task-login #layout-content {
    background: #ffffff;
    border-radius: 20px;
    box-shadow: 0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.05);
    padding: 44px 40px 36px;
    width: 100%;
    max-width: 420px;
    margin: auto;
}

body.task-login #nexiocp-header {
    text-align: center;
    margin-bottom: 32px;
}

body.task-login #logo {
    display: block;
    margin: 0 auto 16px;
    max-height: 48px;
    width: auto;
    max-width: 180px;
}

body.task-login #nexiocp-brand {
    text-align: center;
}

body.task-login #nexiocp-mail-label {
    display: inline-block;
    font-size: 1.4rem;
    font-weight: 800;
    color: #0f172a;
    letter-spacing: -0.5px;
    line-height: 1;
}

body.task-login #nexiocp-brand p {
    font-size: 0.84rem;
    color: #64748b;
    margin: 6px 0 0;
}

body.task-login #nexiocp-header::after {
    content: "";
    display: block;
    width: 40px;
    height: 3px;
    background: linear-gradient(90deg, #2563eb, #60a5fa);
    border-radius: 2px;
    margin: 16px auto 0;
}

body.task-login .propform td.title label {
    font-size: 0.78rem !important;
    font-weight: 700 !important;
    color: #475569 !important;
    text-transform: uppercase !important;
    letter-spacing: 0.6px !important;
    display: block !important;
    margin-bottom: 6px !important;
}

body.task-login input[type=text].form-control,
body.task-login input[type=password].form-control,
body.task-login .form-control {
    border-radius: 10px !important;
    border: 1.5px solid #e2e8f0 !important;
    padding: 11px 14px !important;
    font-size: 0.93rem !important;
    background: #f8fafc !important;
    transition: all 0.2s !important;
    width: 100% !important;
    box-sizing: border-box !important;
}

body.task-login input[type=text].form-control:focus,
body.task-login input[type=password].form-control:focus {
    border-color: #3b82f6 !important;
    box-shadow: 0 0 0 3px rgba(59,130,246,0.12) !important;
    background: #fff !important;
    outline: none !important;
}

body.task-login #rcmloginsubmit {
    background: linear-gradient(135deg, #1d4ed8, #3b82f6) !important;
    border: none !important;
    border-radius: 10px !important;
    color: #fff !important;
    font-weight: 700 !important;
    font-size: 0.95rem !important;
    padding: 13px !important;
    width: 100% !important;
    cursor: pointer !important;
    transition: all 0.2s !important;
    margin-top: 12px !important;
    letter-spacing: 0.5px !important;
    box-shadow: 0 4px 14px rgba(37,99,235,0.4) !important;
}

body.task-login #rcmloginsubmit:hover {
    background: linear-gradient(135deg, #1e40af, #2563eb) !important;
    box-shadow: 0 6px 20px rgba(37,99,235,0.5) !important;
    transform: translateY(-1px) !important;
}

body.task-login table.propform {
    width: 100% !important;
    border-spacing: 0 !important;
    border-collapse: collapse !important;
}

body.task-login table.propform tr {
    display: block !important;
    margin-bottom: 16px !important;
}

body.task-login table.propform td {
    display: block !important;
    width: 100% !important;
    padding: 0 !important;
}

body.task-login #login-footer {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #f1f5f9;
    text-align: center;
    font-size: 0.76rem;
    color: #94a3b8;
}

body.task-login #login-footer::before {
    content: "NexioCP Hosting Panel";
    display: block;
    font-weight: 600;
    color: #64748b;
    margin-bottom: 2px;
}

body.task-login .notice.error {
    border-radius: 10px !important;
    margin-bottom: 16px !important;
    font-size: 0.88rem !important;
}

@media (max-width: 480px) {
    body.task-login #layout-content {
        border-radius: 0 !important;
        padding: 40px 20px 28px !important;
        min-height: 100vh;
        box-shadow: none !important;
    }
}
CSSEOF

        # Roundcube public_html'e symlink ekle
        if [ -d "${RC_PUBSKINS}" ] && [ ! -L "${RC_PUBSKINS}/nexiocp" ]; then
            ln -s "${NEXIO_SKIN}" "${RC_PUBSKINS}/nexiocp"
            ok "Roundcube skins symlink oluşturuldu"
        fi

        # Roundcube config'de skin'i nexiocp olarak ayarla
        RC_CONFIG="/etc/roundcube/config.inc.php"
        if [ -f "${RC_CONFIG}" ]; then
            # PHP son atama kazanır — skin satırını override et
            echo "\$config['skin'] = 'nexiocp';" >> "${RC_CONFIG}"
        fi

        ok "NexioCP Roundcube skin kuruldu: ${NEXIO_SKIN}"
    else
        warn "Elastic skin bulunamadı — NexioCP webmail skin atlandı"
    fi

else
    warn "Roundcube config bulunamadı — webmail SSO manuel yapılandırma gerekebilir"
fi

# ═══════════════════════════════════════════════════════════════════════════════
step "ModSecurity / WAF (derleme bağımlılıkları)"
# ═══════════════════════════════════════════════════════════════════════════════
# ModSecurity-nginx connector kaynak olarak derlenir.
# Ubuntu 22.04 standard repolarında nginx modülü paketi yok,
# panel "WAF Kur" butonuyla derleme + kurulum yapar.
apt-get install -y -qq \
    libmodsecurity3 libmodsecurity-dev modsecurity-crs \
    build-essential git wget \
    libpcre3-dev zlib1g-dev libssl-dev 2>/dev/null \
    && ok "ModSecurity derleme bağımlılıkları hazır" \
    || warn "Bazı ModSecurity bağımlılıkları kurulamadı — panel üzerinden denenebilir"

# ═══════════════════════════════════════════════════════════════════════════════
step "vsftpd (FTP)"
# ═══════════════════════════════════════════════════════════════════════════════
apt-get install -y -qq vsftpd

cat > /etc/vsftpd.conf << 'FTP'
listen=YES
listen_ipv6=NO
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
chroot_local_user=YES
allow_writeable_chroot=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=ftp
ssl_enable=NO
utf8_filesystem=YES
# Pasif mod
pasv_enable=YES
pasv_min_port=40000
pasv_max_port=50000
# Kullanıcı başına konfigürasyon (home dir override)
user_config_dir=/etc/vsftpd/users
# Whitelist modu — sadece listede olan kullanıcılar girebilir
guest_enable=NO
userlist_enable=YES
userlist_file=/etc/vsftpd.userlist
userlist_deny=NO
max_clients=50
max_per_ip=5
FTP

touch /etc/vsftpd.userlist
mkdir -p /var/run/vsftpd/empty

systemctl enable vsftpd
systemctl restart vsftpd

ok "vsftpd kuruldu (pasif port: 40000-50000)"

# ═══════════════════════════════════════════════════════════════════════════════
step "Fail2ban"
# ═══════════════════════════════════════════════════════════════════════════════
apt-get install -y -qq fail2ban

cat > /etc/fail2ban/jail.local << F2B
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5
destemail = root@localhost
backend = auto

[sshd]
enabled  = true
port     = ssh
logpath  = %(sshd_log)s

[nginx-http-auth]
enabled  = true

[nginx-limit-req]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/error.log

[vsftpd]
enabled  = true
port     = ftp,ftp-data,ftps,ftps-data
logpath  = %(vsftpd_log)s

[postfix]
enabled  = true
port     = smtp,465,submission

[dovecot]
enabled  = true
port     = pop3,pop3s,imap,imaps,submission,465,sieve
F2B

systemctl enable fail2ban
systemctl restart fail2ban

ok "Fail2ban kuruldu"

# ═══════════════════════════════════════════════════════════════════════════════
step "phpMyAdmin Yapılandırması"
# ═══════════════════════════════════════════════════════════════════════════════
if [[ -d /usr/share/phpmyadmin ]]; then
    # Signon auth config
    mkdir -p /etc/phpmyadmin/conf.d
    cat > /etc/phpmyadmin/conf.d/nexiocp.php << 'PMAEOF'
<?php
// NexioCP — phpMyAdmin signon auth
$cfg['blowfish_secret'] = ''; // phpMyAdmin kendi üretir
$cfg['Servers'][1]['auth_type']      = 'signon';
$cfg['Servers'][1]['SignonSession']  = 'NexioCPSignonSession';
$cfg['Servers'][1]['SignonURL']      = '/pma-relay.php';
$cfg['Servers'][1]['LogoutURL']      = '';
$cfg['Servers'][1]['host']           = '127.0.0.1';
$cfg['Servers'][1]['port']           = '3306';
$cfg['Servers'][1]['connect_type']   = 'tcp';
$cfg['Servers'][1]['compress']       = false;
$cfg['Servers'][1]['AllowNoPassword'] = false;
$cfg['DefaultLang'] = 'tr';
$cfg['UploadDir'] = '';
$cfg['SaveDir']   = '';
PMAEOF
    ok "phpMyAdmin signon auth yapılandırıldı"
else
    warn "phpMyAdmin kurulmamış, PMA özelliği atlanıyor"
fi

# pma-relay.php — token tabanlı phpMyAdmin otomatik giriş
cat > /var/www/html/pma-relay.php << 'PHPEOF'
<?php
/**
 * NexioCP — phpMyAdmin Signon Relay
 * Token tabanlı tek kullanımlık otomatik giriş scripti
 */
$token = isset($_GET['token']) ? preg_replace('/[^a-f0-9]/', '', $_GET['token']) : '';

if (strlen($token) !== 32) {
    http_response_code(400);
    die('<h2>Geçersiz token</h2><p>NexioCP panelinden phpMyAdmin butonuna tıklayın.</p>');
}

$tokenFile = '/run/nexiocp/pma-tokens/' . $token . '.json';

if (!file_exists($tokenFile)) {
    http_response_code(403);
    die('<h2>Token bulunamadı veya süresi dolmuş</h2><p>NexioCP panelinden tekrar phpMyAdmin butonuna tıklayın.</p>');
}

$data = json_decode(file_get_contents($tokenFile), true);
@unlink($tokenFile); // Tek kullanımlık — sil

if (!$data || empty($data['username']) || empty($data['password'])) {
    http_response_code(500);
    die('<h2>Token verisi hatalı</h2>');
}

// phpMyAdmin signon session ayarla
session_name('NexioCPSignonSession');
session_start();

$_SESSION['PMA_single_signon_user']     = $data['username'];
$_SESSION['PMA_single_signon_password'] = $data['password'];
$_SESSION['PMA_single_signon_host']     = '127.0.0.1';
$_SESSION['PMA_single_signon_port']     = '3306';
$_SESSION['PMA_single_signon_db']       = isset($data['db']) ? $data['db'] : '';

session_write_close();

header('Location: /phpmyadmin/index.php');
exit;
PHPEOF
chmod 644 /var/www/html/pma-relay.php
ok "pma-relay.php oluşturuldu"

# webmail-relay.php — nexiocp_sso plugin'ine yönlendirme
cat > /var/www/html/webmail-relay.php << 'WMEOF'
<?php
/**
 * NexioCP — Webmail SSO Relay
 * Token doğrular, Roundcube nexiocp_sso plugin'ine devredер.
 * Müşteri panelinde (HTTPS) SSO çalışır; admin panelinde /webmail/ login sayfası açılır.
 */
$token = isset($_GET['token']) ? preg_replace('/[^a-f0-9]/', '', $_GET['token']) : '';
if (strlen($token) !== 32) { http_response_code(400); die('Gecersiz token'); }

$tokenFile = '/run/nexiocp/webmail-tokens/' . $token . '.json';
if (!file_exists($tokenFile)) { http_response_code(403); die('Token bulunamadi. Panelden tekrar deneyin.'); }

// Token gecerli - Roundcube SSO plugin'ine devret
header('Location: /webmail/?nexiocp_token=' . $token);
exit;
WMEOF
chmod 644 /var/www/html/webmail-relay.php
ok "webmail-relay.php oluşturuldu"

# ═══════════════════════════════════════════════════════════════════════════════
step "UFW Güvenlik Duvarı"
# ═══════════════════════════════════════════════════════════════════════════════
# SSH portunu otomatik tespit et
# 1. Aktif SSH bağlantısının sunucu portu ($SSH_CONNECTION = "clientIP clientPort serverIP serverPort")
SSH_PORT=$(echo "${SSH_CONNECTION:-}" | awk '{print $4}')
# 2. $SSH_CLIENT fallback ("clientIP clientPort serverPort")
if [[ -z "$SSH_PORT" ]] && [[ -n "${SSH_CLIENT:-}" ]]; then
    SSH_PORT=$(echo "${SSH_CLIENT:-}" | awk '{print $3}')
fi
# 3. ss ile gerçekten dinleyen sshd portunu bul
if [[ -z "$SSH_PORT" ]]; then
    SSH_PORT=$(ss -tnlp 2>/dev/null | grep sshd | awk '{sub(/.*:/, "", $4); print $4}' | head -1)
fi
# 4. sshd_config'e bak
if [[ -z "$SSH_PORT" ]]; then
    SSH_PORT=$(grep -E "^\s*Port\s+" /etc/ssh/sshd_config 2>/dev/null | awk '{print $NF}' | head -1)
fi
# 5. Hiçbiri bulamazsa varsayılan 22
SSH_PORT=${SSH_PORT:-22}

# Kullanıcıya sor — yanlış tespit edilirse UFW sonrası kilitlenmeyi önle
echo ""
echo -e "${YELLOW}${BOLD}  ┌─────────────────────────────────────────────────┐${NC}"
echo -e "${YELLOW}${BOLD}  │  SSH PORT DOĞRULAMA                             │${NC}"
echo -e "${YELLOW}${BOLD}  └─────────────────────────────────────────────────┘${NC}"
echo -e "  Tespit edilen SSH portu: ${BOLD}${CYAN}${SSH_PORT}${NC}"
echo -e "  ${YELLOW}Bu port UFW'ye eklenecek. Yanlışsa sunucudan kilitlenirim!${NC}"
echo -e "  ${WHITE}Doğruysa ENTER, farklıysa port numarasını girin:${NC} "
read -r -t 60 SSH_PORT_INPUT || true
if [[ -n "${SSH_PORT_INPUT:-}" ]] && [[ "${SSH_PORT_INPUT}" =~ ^[0-9]+$ ]]; then
    SSH_PORT="${SSH_PORT_INPUT}"
    info "SSH portu güncellendi: ${SSH_PORT}"
else
    info "SSH portu onaylandı: ${SSH_PORT}"
fi
echo ""

ufw --force reset
ufw default deny incoming
ufw default allow outgoing

ufw allow ${SSH_PORT}/tcp  comment 'SSH'
ufw allow 80/tcp       comment 'HTTP'
ufw allow 443/tcp      comment 'HTTPS'
ufw allow ${PANEL_SSL_PORT}/tcp comment 'NexioCP Panel SSL'
ufw allow 8443/tcp             comment 'NexioCP Panel Cloudflare'
ufw allow 21/tcp       comment 'FTP Control'
ufw allow 20/tcp       comment 'FTP Data'
ufw allow 40000:50000/tcp comment 'FTP Passive'
ufw allow 25/tcp       comment 'SMTP'
ufw allow 587/tcp      comment 'SMTP Submission'
ufw allow 465/tcp      comment 'SMTPS'
ufw allow 993/tcp      comment 'IMAPS'
ufw allow 995/tcp      comment 'POP3S'
ufw allow 110/tcp      comment 'POP3'
ufw allow 143/tcp      comment 'IMAP'

ufw --force enable

ok "UFW güvenlik duvarı yapılandırıldı"


# ═══════════════════════════════════════════════════════════════════════════════
step "Dizinler Oluşturuluyor"
# ═══════════════════════════════════════════════════════════════════════════════
mkdir -p \
    "$PANEL_DIR" \
    "$DATA_DIR" \
    "$LOG_DIR" \
    "$BACKUP_DIR" \
    "$WEBROOT" \
    "$CONFIG_DIR" \
    /var/www/html \
    /run/php

chmod 755  "$PANEL_DIR"
chmod 700  "$DATA_DIR"
chmod 755  "$LOG_DIR"
chmod 755  "$BACKUP_DIR"
chmod 755  "$WEBROOT"

ok "Dizinler hazır"

# ═══════════════════════════════════════════════════════════════════════════════
step "NexioCP Binary İndirilyor"
# ═══════════════════════════════════════════════════════════════════════════════
BINARY_NAME="nexiocp-linux-${ARCH_DL}"
BINARY_URL="${CDN_BASE}/${NEXIOCP_VERSION}/${BINARY_NAME}"

info "İndiriliyor: ${BINARY_URL}"

if ! wget -q --show-progress -O "${PANEL_DIR}/nexiocp" "${BINARY_URL}"; then
    # CDN'den versiyon doğrudan alınamadıysa latest dene
    BINARY_URL="${CDN_BASE}/${BINARY_NAME}"
    info "Alternatif deneniyor: ${BINARY_URL}"
    wget -q --show-progress -O "${PANEL_DIR}/nexiocp" "${BINARY_URL}" \
        || die "Binary indirilemedi. CDN erişimi kontrol edin: ${CDN_BASE}"
fi

chmod 755 "${PANEL_DIR}/nexiocp"

# İndirilen binary'yi doğrula
if ! "${PANEL_DIR}/nexiocp" version &>/dev/null; then
    die "Binary çalıştırılamadı. Mimari uyumsuzluğu olabilir (${ARCH_DL})"
fi

ok "NexioCP binary hazır: ${PANEL_DIR}/nexiocp"

# ═══════════════════════════════════════════════════════════════════════════════
step "Konfigürasyon Oluşturuluyor"
# ═══════════════════════════════════════════════════════════════════════════════
JWT_SECRET=$(openssl rand -base64 64 | tr -dc 'A-Za-z0-9+/' | head -c 64)
CONFIG_FILE="${CONFIG_DIR}/nexiocp.yaml"

cat > "$CONFIG_FILE" << YAML
# NexioCP Panel — Production Config
# Oluşturulma: $(date '+%Y-%m-%d %H:%M:%S')
# Düzenlemek için: nano ${CONFIG_FILE}

dev_mode: false

server:
  host: 127.0.0.1
  port: ${PANEL_PORT}
  tls: false

database:
  path: ${DATA_DIR}/panel.db

web_root: ${WEBROOT}

security:
  jwt_secret: "${JWT_SECRET}"
  jwt_access_ttl: 15m
  jwt_refresh_ttl: 168h
  rate_limit: 60
  auth_rate_limit: 5
  max_login_attempts: 5
  lockout_duration: 15m
  session_timeout: 8h

webserver:
  type: nginx
  config_dir: /etc/nginx/sites-available
  enabled_dir: /etc/nginx/sites-enabled
  reload_cmd: ["systemctl", "reload", "nginx"]

phpfpm:
  versions: ["8.3"]
  config_base: /etc/php
  sock_dir: /run/php

mysql:
  host: localhost
  port: 3306
  root_password_file: ${MYSQL_PASS_FILE}

pgsql:
  host: localhost
  port: 5432
  superuser: postgres

ssl:
  acme_email: "${ACME_EMAIL}"
  webroot: /var/www/html
  cert_dir: /etc/letsencrypt/live

backup:
  local_dir: ${BACKUP_DIR}
  retention_days: 30
  schedule: "0 3 * * *"

email:
  postfix_main: /etc/postfix/main.cf
  postfix_virtual: /etc/postfix/virtual
  postfix_virtual_mailbox: /etc/postfix/virtual_mailbox
  dovecot_passwd: /etc/dovecot/users
  dkim_dir: /etc/opendkim/keys
  rspamd_enabled: false

logging:
  level: info
  file: ${LOG_DIR}/panel.log
  audit_file: ${LOG_DIR}/audit.log
  max_size_mb: 100
  max_backups: 7

monitor:
  collect_interval: 30s
  history_retention: 168h

license:
  server: https://license.nexiocp.com
  check_interval: 3h
  offline_grace: 24h
YAML

chmod 600 "$CONFIG_FILE"
ok "Config oluşturuldu: ${CONFIG_FILE}"

# ═══════════════════════════════════════════════════════════════════════════════
step "Logrotate Yapılandırması"
# ═══════════════════════════════════════════════════════════════════════════════
cat > /etc/logrotate.d/nexiocp << EOF
${LOG_DIR}/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    sharedscripts
    postrotate
        systemctl kill -s HUP nexiocp 2>/dev/null || true
    endscript
}
EOF

ok "Logrotate yapılandırıldı"

# ═══════════════════════════════════════════════════════════════════════════════
step "Systemd Servisi"
# ═══════════════════════════════════════════════════════════════════════════════
cat > /etc/systemd/system/nexiocp.service << EOF
[Unit]
Description=NexioCP Hosting Control Panel
Documentation=https://nexiocp.com/docs
After=network.target network-online.target mysql.service
Wants=network-online.target

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=${PANEL_DIR}
ExecStart=${PANEL_DIR}/nexiocp serve --config ${CONFIG_FILE}
Restart=always
RestartSec=5
StartLimitBurst=5
StartLimitIntervalSec=60
StandardOutput=journal
StandardError=journal
SyslogIdentifier=nexiocp

# Güvenlik kısıtlamaları
PrivateTmp=true
NoNewPrivileges=false
ProtectSystem=false

# Çevre değişkenleri
Environment=HOME=/root

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable nexiocp

ok "Systemd servisi oluşturuldu"

# ═══════════════════════════════════════════════════════════════════════════════
step "Nginx Proxy Yapılandırması"
# ═══════════════════════════════════════════════════════════════════════════════

# Cloudflare origin sertifikası oluştur (Full SSL modu için)
ORIGIN_SSL_DIR="${CONFIG_DIR}/ssl"
mkdir -p "$ORIGIN_SSL_DIR"
if [[ ! -f "${ORIGIN_SSL_DIR}/origin.crt" ]]; then
    openssl req -x509 -nodes -days 3650 \
        -newkey rsa:2048 \
        -keyout "${ORIGIN_SSL_DIR}/origin.key" \
        -out    "${ORIGIN_SSL_DIR}/origin.crt" \
        -subj "/C=TR/ST=Istanbul/L=Istanbul/O=NexioCP/CN=origin" \
        2>/dev/null
    ok "Cloudflare origin sertifikası oluşturuldu: ${ORIGIN_SSL_DIR}/origin.crt"
fi

# Default nginx blokları
# Port 80 + SERVER_IP  → Kapalı (444) — panel sadece 8443 HTTPS üzerinden
# Port 80 + domain     → Domain kendi bloğuna gider (website)
# Port 80 + bilinmeyen → 444 (panel gösterilmez)
# Port 443 + bilinmeyen → 444
cat > /etc/nginx/sites-available/nexiocp-panel << EOF
# Port 80: IP erişimi kapalı — panel sadece https://IP:8443 üzerinden
server {
    listen 80;
    server_name ${SERVER_IP};

    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }

    location / {
        return 444;
    }
}

# Port 80 default: Bilinmeyen domain → kapat (panel gösterilmez)
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }

    location / {
        return 444;
    }
}

# Port 443 default: Bilinmeyen HTTPS → kapat
server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    server_name _;

    ssl_certificate     ${ORIGIN_SSL_DIR}/origin.crt;
    ssl_certificate_key ${ORIGIN_SSL_DIR}/origin.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;

    location / {
        return 444;
    }
}
EOF

ln -sf /etc/nginx/sites-available/nexiocp-panel /etc/nginx/sites-enabled/nexiocp-panel

# Panel proxy — port 8443 (SSL)
# Önce self-signed fallback sertifikası oluştur
SELFSIGN_DIR="${CONFIG_DIR}/ssl"
mkdir -p "$SELFSIGN_DIR"

if [[ ! -f "${SELFSIGN_DIR}/selfsigned.crt" ]]; then
    openssl req -x509 -nodes -days 3650 \
        -newkey rsa:2048 \
        -keyout "${SELFSIGN_DIR}/selfsigned.key" \
        -out    "${SELFSIGN_DIR}/selfsigned.crt" \
        -subj "/C=TR/ST=Istanbul/L=Istanbul/O=NexioCP/CN=${SERVER_IP}" \
        -addext "subjectAltName=IP:${SERVER_IP}" \
        2>/dev/null
fi

# Kullanılacak SSL sertifika — varsayılan: self-signed
PANEL_SSL_CERT="${SELFSIGN_DIR}/selfsigned.crt"
PANEL_SSL_KEY="${SELFSIGN_DIR}/selfsigned.key"
PANEL_SSL_SERVERNAME="_"

# PANEL_DOMAIN verilmişse Let's Encrypt sertifikası al veya mevcut olanı kullan
if [[ -n "${PANEL_DOMAIN:-}" ]]; then
    info "Panel domain: ${PANEL_DOMAIN}"
    # Nginx'i yeniden yükle — ACME challenge location aktif olsun
    nginx -t 2>/dev/null && systemctl reload nginx 2>/dev/null || true

    if [[ -f "/etc/letsencrypt/live/${PANEL_DOMAIN}/fullchain.pem" ]]; then
        # Mevcut LE sertifikası kullan
        PANEL_SSL_CERT="/etc/letsencrypt/live/${PANEL_DOMAIN}/fullchain.pem"
        PANEL_SSL_KEY="/etc/letsencrypt/live/${PANEL_DOMAIN}/privkey.pem"
        PANEL_SSL_SERVERNAME="_"
        ok "Mevcut Let's Encrypt sertifikası: ${PANEL_DOMAIN}"
    else
        # Yeni sertifika al
        CERTBOT_EXTRA=""
        if [[ -n "${ACME_EMAIL:-}" ]]; then
            CERTBOT_EXTRA="--email ${ACME_EMAIL}"
        else
            CERTBOT_EXTRA="--register-unsafely-without-email"
        fi
        if certbot certonly --webroot -w /var/www/html \
            -d "${PANEL_DOMAIN}" \
            --non-interactive --agree-tos \
            ${CERTBOT_EXTRA} 2>/dev/null; then
            PANEL_SSL_CERT="/etc/letsencrypt/live/${PANEL_DOMAIN}/fullchain.pem"
            PANEL_SSL_KEY="/etc/letsencrypt/live/${PANEL_DOMAIN}/privkey.pem"
            PANEL_SSL_SERVERNAME="_"
            ok "Let's Encrypt sertifikası alındı: ${PANEL_DOMAIN}"
        else
            warn "Let's Encrypt alınamadı (DNS henüz yayılmamış olabilir) — self-signed kullanılacak"
        fi
    fi
fi

# phpMyAdmin erişim kontrolü için nginx map bloğu (tüm vhostlarda $pma_allowed kullanılır)
cat > /etc/nginx/conf.d/nexiocp-maps.conf << 'MAPSEOF'
# NexioCP — phpMyAdmin erişim kontrolü (NexioCP tarafından güncellenir)
map $cookie_pma_access $pma_allowed {
    default 0;
}
MAPSEOF

cat > /etc/nginx/conf.d/nexiocp-panel-ssl.conf << EOF
# NexioCP Yönetim Paneli
# Erişim: https://SUNUCU_IP:${PANEL_SSL_PORT}  veya  https://panel.domain.com:${PANEL_SSL_PORT}
# Cloudflare uyumlu alternatif: https://panel.domain.com:8443
server {
    listen ${PANEL_SSL_PORT} ssl http2;
    server_name ${PANEL_SSL_SERVERNAME};

    ssl_certificate     ${PANEL_SSL_CERT};
    ssl_certificate_key ${PANEL_SSL_KEY};
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache   shared:SSL8443:10m;

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;

    client_max_body_size 256m;

    # phpMyAdmin otomatik giriş relay script
    location = /pma-relay.php {
        root /var/www/html;
        fastcgi_pass unix:/run/php/php${DEFAULT_PHP}-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /var/www/html/pma-relay.php;
        fastcgi_param HTTPS on;
    }

    # phpMyAdmin arayüzü
    location /phpmyadmin {
        root /usr/share/;
        index index.php index.html;
        location ~ ^/phpmyadmin/(.+\.php)$ {
            try_files \$uri =404;
            root /usr/share/;
            fastcgi_pass unix:/run/php/php${DEFAULT_PHP}-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
            fastcgi_param HTTPS on;
        }
        location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
            root /usr/share/;
        }
    }

    # Webmail SSO relay script
    location = /webmail-relay.php {
        root /var/www/html;
        fastcgi_pass unix:/run/php/php${DEFAULT_PHP}-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /var/www/html/webmail-relay.php;
        fastcgi_param HTTPS on;
    }

    # Roundcube webmail arayüzü
    location /webmail {
        root /usr/share/;
        index index.php index.html;
        location ~ ^/webmail/(.+\.php)$ {
            try_files \$uri =404;
            root /usr/share/;
            fastcgi_pass unix:/run/php/php${DEFAULT_PHP}-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
            fastcgi_param HTTPS on;
        }
        location ~* ^/webmail/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt|woff|woff2|eot|ttf|svg))$ {
            root /usr/share/;
            expires 7d;
        }
    }

    location / {
        proxy_pass         http://127.0.0.1:${PANEL_PORT};
        proxy_http_version 1.1;
        proxy_set_header   Upgrade            \$http_upgrade;
        proxy_set_header   Connection         "upgrade";
        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;
        proxy_read_timeout 300s;
    }
}
EOF

nginx -t && systemctl restart nginx

ok "Nginx yapılandırıldı (80 + ${PANEL_SSL_PORT})"

# ═══════════════════════════════════════════════════════════════════════════════
# webmail.PANEL_DOMAIN — Roundcube için ayrı nginx vhost + Let's Encrypt
# ═══════════════════════════════════════════════════════════════════════════════
if [[ -n "${PANEL_DOMAIN:-}" ]]; then
    WEBMAIL_DOMAIN="webmail.${PANEL_DOMAIN}"
    info "Webmail vhost oluşturuluyor: ${WEBMAIL_DOMAIN}"

    # Geçici HTTP vhost (certbot challenge için)
    cat > "/etc/nginx/sites-available/${WEBMAIL_DOMAIN}.conf" << WMEOF
server {
    listen 80;
    server_name ${WEBMAIL_DOMAIN};

    location ^~ /.well-known/acme-challenge/ {
        root /var/lib/roundcube/public_html;
        allow all;
    }

    location / {
        return 301 https://\$host\$request_uri;
    }
}
WMEOF
    ln -sf "/etc/nginx/sites-available/${WEBMAIL_DOMAIN}.conf" \
           "/etc/nginx/sites-enabled/${WEBMAIL_DOMAIN}.conf"
    nginx -t 2>/dev/null && systemctl reload nginx 2>/dev/null || true

    # Let's Encrypt sertifikası al
    CERTBOT_EXTRA_WM=""
    if [[ -n "${ACME_EMAIL:-}" ]]; then
        CERTBOT_EXTRA_WM="--email ${ACME_EMAIL}"
    else
        CERTBOT_EXTRA_WM="--register-unsafely-without-email"
    fi

    WEBMAIL_CERT="/etc/nexiocp/ssl/origin.crt"
    WEBMAIL_KEY="/etc/nexiocp/ssl/origin.key"

    if [[ -f "/etc/letsencrypt/live/${WEBMAIL_DOMAIN}/fullchain.pem" ]]; then
        WEBMAIL_CERT="/etc/letsencrypt/live/${WEBMAIL_DOMAIN}/fullchain.pem"
        WEBMAIL_KEY="/etc/letsencrypt/live/${WEBMAIL_DOMAIN}/privkey.pem"
        ok "Mevcut Let's Encrypt sertifikası kullanıldı: ${WEBMAIL_DOMAIN}"
    elif certbot certonly --webroot -w /var/lib/roundcube/public_html \
            -d "${WEBMAIL_DOMAIN}" \
            --non-interactive --agree-tos \
            ${CERTBOT_EXTRA_WM} 2>/dev/null; then
        WEBMAIL_CERT="/etc/letsencrypt/live/${WEBMAIL_DOMAIN}/fullchain.pem"
        WEBMAIL_KEY="/etc/letsencrypt/live/${WEBMAIL_DOMAIN}/privkey.pem"
        ok "Let's Encrypt sertifikası alındı: ${WEBMAIL_DOMAIN}"
    else
        warn "Let's Encrypt alınamadı — self-signed sertifika kullanılacak: ${WEBMAIL_DOMAIN}"
    fi

    # Tam HTTPS vhost
    cat > "/etc/nginx/sites-available/${WEBMAIL_DOMAIN}.conf" << WMEOF
server {
    listen 80;
    server_name ${WEBMAIL_DOMAIN};

    location ^~ /.well-known/acme-challenge/ {
        root /var/lib/roundcube/public_html;
        allow all;
    }

    location / {
        return 301 https://\$host\$request_uri;
    }
}

server {
    listen 443 ssl http2;
    server_name ${WEBMAIL_DOMAIN};
    root /var/lib/roundcube/public_html;
    index index.php index.html;

    ssl_certificate     ${WEBMAIL_CERT};
    ssl_certificate_key ${WEBMAIL_KEY};
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    add_header Strict-Transport-Security "max-age=63072000" always;

    access_log /var/log/nginx/${WEBMAIL_DOMAIN}.access.log;
    error_log  /var/log/nginx/${WEBMAIL_DOMAIN}.error.log;

    client_max_body_size 32M;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    location ~ \.php$ {
        try_files \$uri =404;
        fastcgi_pass unix:/run/php/php${DEFAULT_PHP}-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_param HTTPS on;
    }

    location ^~ /.well-known/acme-challenge/ {
        root /var/lib/roundcube/public_html;
        allow all;
    }

    location ~ /\. {
        deny all;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff2|svg)$ {
        expires 30d;
    }
}
WMEOF
    nginx -t 2>/dev/null && systemctl reload nginx 2>/dev/null || true
    ok "Webmail nginx vhost tamamlandı: https://${WEBMAIL_DOMAIN}"
fi

# ═══════════════════════════════════════════════════════════════════════════════
step "NexioCP Başlatılıyor"
# ═══════════════════════════════════════════════════════════════════════════════
systemctl start nexiocp
sleep 4

if ! systemctl is-active --quiet nexiocp; then
    echo ""
    warn "NexioCP başlatılamadı! Son loglar:"
    journalctl -u nexiocp -n 30 --no-pager || true
    echo ""
    die "Kurulum başarısız. Yukarıdaki hataları inceleyin."
fi

# Sağlık kontrolü
HEALTH=$(curl -s --max-time 5 http://127.0.0.1:${PANEL_PORT}/api/v1/health 2>/dev/null || echo "")
if echo "$HEALTH" | grep -q '"status":"ok"'; then
    ok "Sağlık kontrolü geçti (/api/v1/health → ok)"
else
    warn "Sağlık kontrolü yanıt vermedi — servis yavaş başlıyor olabilir"
fi

# ═══════════════════════════════════════════════════════════════════════════════
# ÖZET
# ═══════════════════════════════════════════════════════════════════════════════
echo ""
echo -e "${GREEN}${BOLD}"
echo "  ╔══════════════════════════════════════════════════════════╗"
echo "  ║                                                          ║"
echo "  ║          NEXIOCP KURULUMU TAMAMLANDI!  🎉               ║"
echo "  ║                                                          ║"
echo "  ╚══════════════════════════════════════════════════════════╝"
echo -e "${NC}"

echo -e "${BOLD}  Panel Erişimi${NC}"
echo -e "  ─────────────────────────────────────────────────────────"
echo -e "  HTTP   : ${CYAN}http://${SERVER_IP}${NC}"
if [[ "${PANEL_SSL_SERVERNAME}" == "_" ]]; then
    echo -e "  HTTPS  : ${CYAN}https://${SERVER_IP}:${PANEL_SSL_PORT}${NC}  ${YELLOW}(sertifika uyarısı → devam et)${NC}"
    echo ""
    echo -e "  ${YELLOW}İpucu: Domain ile HTTPS kurmak için:${NC}"
    echo -e "  ${CYAN}PANEL_DOMAIN=panel.DOMAININIZ bash install.sh${NC}"
else
    echo -e "  HTTPS  : ${CYAN}https://${PANEL_SSL_SERVERNAME}:${PANEL_SSL_PORT}${NC}  ${GREEN}(Let's Encrypt ✓)${NC}"
    echo -e "  ${YELLOW}Not: Cloudflare kullanıyorsanız DNS kaydını 'DNS only' (gri bulut) yapın.${NC}"
fi
echo ""

echo -e "${BOLD}  Dosya Konumları${NC}"
echo -e "  ─────────────────────────────────────────────────────────"
echo -e "  Binary      : ${PANEL_DIR}/nexiocp"
echo -e "  Config      : ${CONFIG_FILE}"
echo -e "  Veritabanı  : ${DATA_DIR}/panel.db"
echo -e "  Loglar      : ${LOG_DIR}/"
echo -e "  Yedekler    : ${BACKUP_DIR}/"
echo -e "  Web root    : ${WEBROOT}/"
echo ""

echo -e "${BOLD}  Veritabanı${NC}"
echo -e "  ─────────────────────────────────────────────────────────"
echo -e "  MySQL root  : ${YELLOW}$(cat ${MYSQL_PASS_FILE})${NC}"
echo -e "  MySQL şifre dosyası: ${MYSQL_PASS_FILE}"
echo ""

echo -e "${BOLD}  Servis Komutları${NC}"
echo -e "  ─────────────────────────────────────────────────────────"
echo -e "  Durum  : systemctl status nexiocp"
echo -e "  Loglar : journalctl -u nexiocp -f"
echo -e "  Yeniden başlat : systemctl restart nexiocp"
echo ""

echo -e "${BOLD}${GREEN}  Sonraki Adım:${NC}"
echo -e "  ─────────────────────────────────────────────────────────"
echo -e "  ${BOLD}Tarayıcıdan açın:${NC}"
echo -e "  ${CYAN}https://${SERVER_IP}${NC}"
echo ""
echo -e "  Kurulum sihirbazı açılacak. Buradan admin hesabınızı"
echo -e "  oluşturun ve paneli kullanmaya başlayın."
echo ""
echo -e "${BOLD}  PHP Sürümleri${NC}"
echo -e "  ─────────────────────────────────────────────────────────"
echo -e "  Kurulu  : PHP 8.3"
echo -e "  Diğerleri (5.6, 7.x, 8.x): ${CYAN}Panel → PHP Yönetimi → PHP Sürüm Yönetimi${NC}"
echo ""

if [[ -n "$ACME_EMAIL" ]]; then
    echo -e "${BOLD}  HTTPS (Let's Encrypt) Kurmak İçin:${NC}"
    echo -e "  ─────────────────────────────────────────────────────"
    echo -e "  certbot --nginx -d DOMAININIZ -m ${ACME_EMAIL} --agree-tos -n"
    echo ""
fi

echo -e "${BOLD}  SSH Portu${NC}"
echo -e "  ─────────────────────────────────────────────────────────"
echo -e "  SSH port  : ${CYAN}${SSH_PORT}${NC}  ${YELLOW}(UFW'de açık)${NC}"
echo ""

echo -e "${YELLOW}  Not: Eğer panel açılmıyorsa güvenlik duvarı kontrolü yapın:${NC}"
echo -e "  ufw status"
echo ""
