#!/bin/bash
#
# desplega_pterodactyl.sh
# -----------------------------------------------------------------------------
# S'executa des del servidor "M" i desplega Pterodactyl (codi obert, MIT) de
# forma desatesa. Té dos modes:
#
#   MODE PANELL  (sense -n)
#     Instal·la al servidor "P": Apache + PHP 8.3 + MariaDB + Redis + panell
#     + Wings/Docker, i dona d'alta "P" com a primer node.
#
#   MODE NODE    (amb -n)
#     Prepara un VPS nou (Docker + Wings + certificat), el dona d'alta al
#     panell de "P", hi crea els ports de joc i el deixa connectat.
#     L'equivalent a afegir un daemon nou a Multicraft.
#
# En tots dos casos: demana la contrasenya de root de cada servidor UNA sola
# vegada (per instal·lar-hi la clau SSH) i no deixa cap fitxer de script als
# servidors remots.
#
# A més, sempre:
#   - Bloqueja la capacitat de jugadors a tots els eggs (només l'admin la
#     canvia; a Minecraft, Wings reescriu max-players a cada arrencada).
#   - Posa allowed_origins al config.yml de Wings (panell i nodes) perquè la
#     consola web funcioni.
#   Si el panell ja existeix, el mode panell només fa aquest manteniment:
#   torna-ho a executar després d'importar eggs nous.
#
# Ús:
#   Panell: ./desplega_pterodactyl.sh -s <panell> [-m <email>] [-ssl false] [-p <ports>]
#   Node:   ./desplega_pterodactyl.sh -s <panell> -n <node> [-m <email>] [-p <ports>]
#
#   -s    Subdomini del panell (p. ex. panel.alexmf.cat). Apunta a "P".
#   -n    Subdomini del node nou (p. ex. node2.alexmf.cat). Apunta al VPS nou.
#   -m    Email de l'administrador i de Let's Encrypt.
#   -ssl  Amb "false" el panell NO fa servir SSL (només mode panell; en mode
#         node se segueix automàticament el que faci el panell).
#   -p    Rang de ports de joc del node (per defecte 25565-25575).
#
# Exemples:
#   ./desplega_pterodactyl.sh -s panel.alexmf.cat
#   ./desplega_pterodactyl.sh -s panel.alexmf.cat -n node2.alexmf.cat
#   ./desplega_pterodactyl.sh -s panel.alexmf.cat -n node3.alexmf.cat -p 25600-25650
#
# Sistemes suportats: Ubuntu 22.04 / 24.04, Debian 11 / 12 / 13.
# -----------------------------------------------------------------------------


# =============================================================================
#  Missatges amb color (a la màquina local "M")
# =============================================================================
ok()   { echo -e "\e[0;32m(-) OK: \e[1;32m$1\e[0m"; }
info() { echo -e "\e[0;36m(?) INFO: \e[1;36m$1\e[0m"; }
warn() { echo -e "\e[0;33m(!) WARNING: \e[1;33m$1\e[0m"; }
err()  { echo -e "\e[0;31m(X) ERROR: \e[1;31m$1\e[0m"; }


# =============================================================================
#  Variables
# =============================================================================
usuario="root"
subdominio=""
nodo=""
nossl=""
email_admin="alexmfv3@gmail.com"
ports_jocs="25565-25575"

regex_subdominio='^([A-Za-z0-9](-?[A-Za-z0-9])*\.)+[A-Za-z]{2,}$'
regex_email='^[^@[:space:]]+@[^@[:space:]]+\.[A-Za-z]{2,}$'
regex_ports='^[0-9]{4,5}-[0-9]{4,5}$'

SSH_OPTS=(-o StrictHostKeyChecking=no -o LogLevel=ERROR)


# =============================================================================
#  Arguments
# =============================================================================
while [[ $# -gt 0 ]]; do
    case "$1" in
        -s)   subdominio="$2";  shift 2 ;;
        -n)   nodo="$2";        shift 2 ;;
        -m)   email_admin="$2"; shift 2 ;;
        -ssl) nossl="$2";       shift 2 ;;
        -p)   ports_jocs="$2";  shift 2 ;;
        *)    err "Opció desconeguda: \e[0;33m$1\e[1;31m."; exit 1 ;;
    esac
done


# =============================================================================
#  Validacions
# =============================================================================
valida_host() {
    local host="$1" opcio="$2"
    if [[ ! "$host" =~ $regex_subdominio ]]; then
        err "El subdomini \e[0;33m${host}\e[1;31m (${opcio}) NO té un format vàlid."
        exit 1
    fi
    if ! ping -c 1 -W 3 "$host" &>/dev/null; then
        err "\e[0;33m${host}\e[1;31m no s'ha pogut resoldre o no respon al PING."
        exit 1
    fi
}

if [[ -z "$subdominio" ]]; then
    info "Has de definir el subdomini del panell amb l'opció \e[0;37m-s\e[1;36m."
    exit 1
fi
valida_host "$subdominio" "-s"

if [[ -n "$nodo" ]]; then
    valida_host "$nodo" "-n"
    if [[ "${nodo,,}" == "${subdominio,,}" ]]; then
        err "El node (-n) no pot ser el mateix subdomini que el panell (-s)."
        exit 1
    fi
fi

if [[ ! "$email_admin" =~ $regex_email ]]; then
    err "L'email \e[0;33m${email_admin}\e[1;31m NO té un format vàlid."
    exit 1
fi

if [[ ! "$ports_jocs" =~ $regex_ports ]] || (( ${ports_jocs%-*} >= ${ports_jocs#*-} )); then
    err "El rang de ports \e[0;33m${ports_jocs}\e[1;31m NO és vàlid (format: 25565-25575)."
    exit 1
fi


# =============================================================================
#  Accés per clau SSH a un servidor remot
#    $1 = host
# =============================================================================
if [[ ! -f "$HOME/.ssh/id_rsa.pub" ]]; then
    ssh-keygen -t rsa -b 4096 -f "$HOME/.ssh/id_rsa" -N "" -q
    ok "S'ha creat la clau pública SSH local."
fi

asegura_clau() {
    local host="$1" salida estado

    salida=$(ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=8 \
                 "$usuario@$host" true 2>&1)
    estado=$?

    if echo "$salida" | grep -q "REMOTE HOST IDENTIFICATION HAS CHANGED"; then
        warn "La identificació de \e[0;33m${host}\e[1;33m ha canviat. Actualitzo la clau coneguda."
        ssh-keygen -R "$host" >/dev/null 2>&1
        estado=1
    fi

    if [[ $estado -eq 0 ]]; then
        ok "Ja hi havia accés per clau SSH a \e[0;33m${host}\e[1;32m."
        return 0
    fi

    warn "Introdueix la contrasenya de root de \e[0;33m${host}\e[1;33m (només aquesta vegada)."
    if command -v ssh-copy-id >/dev/null 2>&1; then
        ssh-copy-id -o StrictHostKeyChecking=no -i "$HOME/.ssh/id_rsa.pub" \
                    "$usuario@$host" 2>/dev/null
    else
        ssh -o StrictHostKeyChecking=no "$usuario@$host" \
            "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys" \
            < "$HOME/.ssh/id_rsa.pub"
    fi

    if ssh -o BatchMode=yes -o StrictHostKeyChecking=no "$usuario@$host" true 2>/dev/null; then
        ok "Clau SSH instal·lada correctament a \e[0;33m${host}\e[1;32m."
    else
        err "No s'ha pogut establir l'accés per clau a \e[0;33m${host}\e[1;31m."
        exit 1
    fi
}


# =============================================================================
#  CODI REMOT COMÚ (panell i nodes)
#  Els here-docs van entre cometes simples: res no s'expandeix localment.
#  Les variables s'injecten amb printf %q (preàmbul) i tot s'envia per stdin
#  a «bash -s», de manera que no queda cap fitxer de script al servidor.
# =============================================================================
remote_comuns=$(cat <<'REMOTE'
set -u

e_ok()   { echo -e "\e[0;32m(-) OK: \e[1;32m$1\e[0m"; }
e_info() { echo -e "\e[0;34m(?) INFO: \e[1;34m$1\e[0m"; }
e_warn() { echo -e "\e[0;33m(!) WARNING: \e[1;33m$1\e[0m"; }
e_err()  { echo -e "\e[0;31m(X) ERROR: \e[1;31m$1\e[0m"; }

PHP_VER="8.3"                         # Pterodactyl 1.x: PHP 8.2 o 8.3
PANEL_DIR="/var/www/pterodactyl"
DB_NAME="panel"
DB_USER="pterodactyl"
CREDENCIALS="/root/pterodactyl_credencials.txt"

export DEBIAN_FRONTEND=noninteractive
APT="-o DPkg::Lock::Timeout=300"

# Executa una ordre en silenci; si falla, mostra les últimes línies de l'error.
silenci() {
    local out
    if ! out=$("$@" 2>&1); then
        e_err "Ha fallat: $*"
        echo "$out" | tail -n 15
        return 1
    fi
}

# Contrasenya aleatòria només alfanumèrica (sense problemes de cometes).
genera_pw() {
    LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c "${1:-24}"
}

# Comprova root i sistema operatiu suportat.
comprova_sistema() {
    if [[ $EUID -ne 0 ]]; then
        e_err "S'ha d'executar com a root."
        exit 1
    fi
    . /etc/os-release
    OS_ID="${ID:-}"; OS_VER="${VERSION_ID:-}"; OS_CODENAME="${VERSION_CODENAME:-}"
    case "${OS_ID}:${OS_VER}" in
        ubuntu:22.04|ubuntu:24.04|debian:11|debian:12|debian:13) ;;
        *)
            e_err "Sistema no suportat: ${PRETTY_NAME:-desconegut}."
            e_err "Fes servir Ubuntu 22.04/24.04 o Debian 11/12/13."
            exit 1
            ;;
    esac
    e_info "$(hostname): \e[0;33m${PRETTY_NAME}\e[1;34m."
}

# Dependències bàsiques.
instala_basics() {
    e_info "Instal·lant dependències bàsiques..."
    silenci apt-get $APT update || exit 1
    silenci apt-get $APT install -y curl ca-certificates gnupg lsb-release \
            apt-transport-https tar unzip git openssl cron || exit 1
}

# Obre els ports al tallafoc (només si hi ha ufw).
#   $@ = regles (p. ex. 80/tcp 25565:25575/udp)
obre_ports() {
    command -v ufw >/dev/null 2>&1 || return 0
    e_info "Obrint ports al tallafoc (ufw)..."
    local regla
    for regla in "$@"; do
        ufw allow "$regla" >/dev/null 2>&1
    done
}

# Docker + binari de Wings + servei systemd (NO l'arrenca: falta config.yml).
instala_wings() {
    if ! command -v docker >/dev/null 2>&1; then
        e_info "Instal·lant Docker..."
        curl -sSL https://get.docker.com/ | CHANNEL=stable bash >/dev/null 2>&1 \
            || { e_err "No s'ha pogut instal·lar Docker."; exit 1; }
    fi
    systemctl enable --now docker >/dev/null 2>&1

    e_info "Instal·lant Wings..."
    mkdir -p /etc/pterodactyl /var/lib/pterodactyl/volumes
    local arq
    arq=$([[ "$(uname -m)" == "x86_64" ]] && echo "amd64" || echo "arm64")
    curl -fsSLo /usr/local/bin/wings \
        "https://github.com/pterodactyl/wings/releases/latest/download/wings_linux_${arq}" \
        || { e_err "No s'ha pogut descarregar Wings."; exit 1; }
    chmod u+x /usr/local/bin/wings

    cat > /etc/systemd/system/wings.service <<'EOF'
[Unit]
Description=Pterodactyl Wings Daemon
After=docker.service
Requires=docker.service
PartOf=docker.service

[Service]
User=root
WorkingDirectory=/etc/pterodactyl
LimitNOFILE=4096
PIDFile=/var/run/wings/daemon.pid
ExecStart=/usr/local/bin/wings
Restart=on-failure
StartLimitInterval=180
StartLimitBurst=30
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
}

# Recursos de la màquina (en MB) per donar d'alta el node.
ram_mb()  { free -m | awk '/^Mem:/ {print $2}'; }
disc_mb() { mkdir -p /var/lib/pterodactyl; df -m --output=avail /var/lib/pterodactyl | tail -n1 | tr -d ' '; }

# ---- Funcions que s'executen al PANELL ----

# Crea (o reutilitza) la localització i el node; hi afegeix els ports de joc.
# Deixa l'ID del node a la variable NODE_ID.
#   $1 = fqdn  $2 = esquema (http/https)  $3 = RAM MB  $4 = disc MB  $5 = ports
registra_node() {
    local fqdn="$1" esquema="$2" ram="$3" disc="$4" ports="$5" loc_id n_ports
    cd "$PANEL_DIR" || exit 1

    loc_id=$(mysql -N -u root "$DB_NAME" -e "SELECT id FROM locations WHERE short='local' LIMIT 1;")
    if [[ -z "$loc_id" ]]; then
        silenci php artisan p:location:make --no-interaction \
            --short=local --long="Servidors propis" || exit 1
        loc_id=$(mysql -N -u root "$DB_NAME" -e "SELECT id FROM locations WHERE short='local' LIMIT 1;")
    fi

    NODE_ID=$(mysql -N -u root "$DB_NAME" -e "SELECT id FROM nodes WHERE fqdn='${fqdn}' LIMIT 1;")
    if [[ -n "$NODE_ID" ]]; then
        e_warn "El node \e[0;33m${fqdn}\e[1;33m ja existia al panell (ID ${NODE_ID}); el reutilitzo."
    else
        e_info "Donant d'alta el node \e[0;33m${fqdn}\e[1;34m (${ram} MB RAM, ${disc} MB disc)..."
        silenci php artisan p:node:make --no-interaction \
            --name="${fqdn%%.*}" --description="Wings a ${fqdn}" \
            --locationId="$loc_id" --fqdn="$fqdn" --public=1 \
            --scheme="$esquema" --proxy=0 --maintenance=0 \
            --maxMemory="$ram" --overallocateMemory=0 \
            --maxDisk="$disc" --overallocateDisk=0 \
            --uploadSize=100 --daemonListeningPort=8080 --daemonSFTPPort=2022 \
            --daemonBase=/var/lib/pterodactyl/volumes || exit 1
        NODE_ID=$(mysql -N -u root "$DB_NAME" -e "SELECT id FROM nodes WHERE fqdn='${fqdn}' LIMIT 1;")
    fi

    # Ports de joc. IP 0.0.0.0 = totes les interfícies (funciona encara que la
    # IP pública no sigui a la interfície); l'àlies mostra el subdomini.
    n_ports=$(mysql -N -u root "$DB_NAME" -e "SELECT COUNT(*) FROM allocations WHERE node_id=${NODE_ID};")
    if [[ "$n_ports" -eq 0 ]]; then
        silenci php artisan tinker --execute="app(\Pterodactyl\Services\Allocations\AssignmentService::class)->handle(\Pterodactyl\Models\Node::findOrFail(${NODE_ID}), ['allocation_ip' => '0.0.0.0', 'allocation_alias' => '${fqdn}', 'allocation_ports' => ['${ports}']]);" \
            || e_warn "No s'han pogut crear els ports; afegeix-los des del panell (Nodes > Allocation)."
    fi

    # Les ordres artisan s'han executat com a root: retornem els permisos.
    chown -R www-data:www-data "${PANEL_DIR}"/*
}

# Bloqueja la capacitat de jugadors a TOTS els eggs del panell.
#  - Les variables de jugadors (MAX_PLAYERS, SLOTS, MAX_USERS...) passen a
#    "no editables" per l'usuari: les veu, però només l'admin les canvia
#    (Admin > Servers > Startup).
#  - Als eggs de Minecraft (server.properties) i BungeeCord (config.yml) es
#    crea MAX_PLAYERS si no hi és i Wings reescriu max-players / player_limit
#    a CADA arrencada: si el client toca el fitxer, es desfà en reiniciar.
# És idempotent: es pot tornar a executar després d'importar eggs nous.
bloqueja_jugadors() {
    e_info "Bloquejant la capacitat de jugadors a tots els eggs..."
    local sortida
    if ! sortida=$(BJ_DSN="${BJ_DSN:-mysql:unix_socket=/run/mysqld/mysqld.sock;dbname=${DB_NAME}}" php <<'PHP' 2>&1
<?php
$db = new PDO(getenv('BJ_DSN'), getenv('BJ_USER') ?: 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$ara = date('Y-m-d H:i:s');

$patroEnv = '/^(SERVER_|SRV_|GAME_)?(MAX_?PLAYERS?|MAXPLAYERS|PLAYERS|PLAYER_?(LIMIT|COUNT|SLOTS)|MAX_?SLOTS|SLOTS|MAX_?USERS|MAX_?CLIENTS)$/i';
$patroNom = '/max(imum)?[\s_-]*(players|slots|users|clients)|(player|slot)s?[\s_-]*(limit|count|max)|jugadors|capacitat/i';

// Fitxers de configuració que fixen els jugadors i com es diuen allà.
$fitxers = [
    'server.properties' => ['max-players'],
    'config.yml'        => ['player_limit', 'listeners[0].max_players'],
];

$eggs = [];
foreach ($db->query('SELECT id, name, config_from, config_files FROM eggs') as $e) {
    $eggs[(int) $e['id']] = $e;
}

$varsDe = function (int $eggId) use ($db) {
    $q = $db->prepare('SELECT id, name, env_variable, user_editable FROM egg_variables WHERE egg_id = ?');
    $q->execute([$eggId]);
    return $q->fetchAll(PDO::FETCH_ASSOC);
};

$cfgDe = function ($egg) {
    $c = json_decode((string) $egg['config_files']);
    return is_object($c) ? $c : null;
};

// Fitxer de jugadors (server.properties / config.yml) que fa servir l'egg,
// propi o heretat (config_from). Retorna [egg propietari, nom del fitxer].
$fitxerDe = function ($egg) use (&$eggs, $cfgDe, $fitxers) {
    for ($salts = 0; $egg && $salts < 5; $salts++) {
        $c = $cfgDe($egg);
        if ($c && count((array) $c)) {
            foreach ($fitxers as $f => $_) {
                if (isset($c->$f->find) && ($f !== 'config.yml' || isset($c->$f->find->{'listeners[0].host'}))) {
                    return [(int) $egg['id'], $f];
                }
            }
            return null;
        }
        $egg = $egg['config_from'] ? ($eggs[(int) $egg['config_from']] ?? null) : null;
    }
    return null;
};

$bloquejades = 0; $creades = 0; $fitxersFixats = 0;
$varPerEgg = [];

foreach ($eggs as $id => $egg) {
    $trobada = null;
    foreach ($varsDe($id) as $v) {
        if (!preg_match($patroEnv, $v['env_variable']) && !preg_match($patroNom, $v['name'])) {
            continue;
        }
        $trobada = $trobada ?? $v['env_variable'];
        if ((int) $v['user_editable'] !== 0) {
            $db->prepare('UPDATE egg_variables SET user_editable = 0, user_viewable = 1, updated_at = ? WHERE id = ?')
               ->execute([$ara, $v['id']]);
            $bloquejades++;
        }
    }

    // Eggs amb fitxer de jugadors: cal una variable per poder-lo fixar.
    if (!$trobada && $fitxerDe($egg)) {
        $db->prepare('INSERT INTO egg_variables (egg_id, name, description, env_variable, default_value,
                          user_viewable, user_editable, rules, created_at, updated_at)
                      VALUES (?, ?, ?, ?, ?, 1, 0, ?, ?, ?)')
           ->execute([$id, 'Màxim de jugadors',
                      "Capacitat de jugadors del servidor. Només l'administrador la pot canviar.",
                      'MAX_PLAYERS', '20', 'required|integer|between:1,1000', $ara, $ara]);
        $varId = (int) $db->lastInsertId();
        $s = $db->prepare('SELECT id FROM servers WHERE egg_id = ?');
        $s->execute([$id]);
        $ins = $db->prepare('INSERT INTO server_variables (server_id, variable_id, variable_value, created_at, updated_at)
                             VALUES (?, ?, ?, ?, ?)');
        foreach ($s->fetchAll(PDO::FETCH_COLUMN) as $srv) {
            $ins->execute([$srv, $varId, '20', $ara, $ara]);
        }
        $trobada = 'MAX_PLAYERS';
        $creades++;
    }
    $varPerEgg[$id] = $trobada;
}

// Fixem el valor als fitxers de configuració (només a l'egg que els defineix).
foreach ($eggs as $id => $egg) {
    $f = $fitxerDe($egg);
    if (!$f || $f[0] !== $id || !$varPerEgg[$id]) {
        continue;
    }
    $c = $cfgDe($egg);
    $canvi = false;
    foreach ($fitxers[$f[1]] as $clau) {
        $valor = '{{server.build.env.' . $varPerEgg[$id] . '}}';
        if (($c->{$f[1]}->find->$clau ?? null) !== $valor) {
            $c->{$f[1]}->find->$clau = $valor;
            $canvi = true;
        }
    }
    if ($canvi) {
        $db->prepare('UPDATE eggs SET config_files = ?, updated_at = ? WHERE id = ?')
           ->execute([json_encode($c, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $ara, $id]);
        $fitxersFixats++;
    }
}

printf("%d eggs revisats · %d variables bloquejades · %d MAX_PLAYERS creades · %d configuracions fixades\n",
       count($eggs), $bloquejades, $creades, $fitxersFixats);
PHP
    ); then
        e_warn "No s'ha pogut bloquejar la capacitat de jugadors:"
        echo "$sortida" | tail -n 10
        return 0
    fi
    e_ok "Jugadors bloquejats: ${sortida}"
}
REMOTE
)


# =============================================================================
#  Orígens permesos de Wings (perquè la consola funcioni)
#  Llegeix el config.yml de Wings per stdin i el treu per stdout amb
#  allowed_origins = panell (https i http). Substitueix el que hi hagués.
#    $1 = subdomini del panell
#  Es fa servir en local (mode node) i s'injecta al codi remot (mode panell).
# =============================================================================
posa_origens() {
    awk -v host="$1" '
        /^allowed_origins:/            { salta = 1; next }
        /^allow_cors_private_network:/ { next }
        salta && /^[[:space:]]+-/      { next }
                                       { salta = 0; print }
        END {
            print "allowed_origins:"
            print "  - https://" host
            print "  - http://" host
            print "allow_cors_private_network: true"
        }'
}
remote_comuns+=$'\n'"$(declare -f posa_origens)"


# =============================================================================
#  CODI REMOT: instal·lació del PANELL a "P"
# =============================================================================
remote_panell=$(cat <<'REMOTE'
if [[ "$OMITIR_SSL" == "false" ]]; then usar_ssl="no"; else usar_ssl="si"; fi

comprova_sistema

# Escriu el config.yml de Wings de "P" amb els orígens del panell.
configura_wings_local() {
    local cfg
    cfg=$(cd "$PANEL_DIR" && php artisan p:node:configuration "$1" --format=yaml) \
        || { e_err "No s'ha pogut generar la configuració de Wings."; exit 1; }
    ( umask 077; posa_origens "$SUBDOMINIO" <<< "$cfg" > /etc/pterodactyl/config.yml )
    e_ok "Consola: orígens permesos a Wings (https/http://${SUBDOMINIO})."
}

if [[ -f "${PANEL_DIR}/.env" ]]; then
    e_info "Pterodactyl ja està instal·lat a ${PANEL_DIR}; només faig el manteniment."
    bloqueja_jugadors
    NODE_ID=$(mysql -N -u root "$DB_NAME" -e "SELECT id FROM nodes WHERE fqdn='${SUBDOMINIO}' LIMIT 1;")
    if [[ -n "$NODE_ID" && -f /etc/pterodactyl/config.yml ]]; then
        configura_wings_local "$NODE_ID"
        systemctl restart wings
    fi
    chown -R www-data:www-data "${PANEL_DIR}"/*
    e_info "Per afegir nodes, fes servir l'opció -n."
    exit 0
fi

instala_basics

# ---- Repositori de PHP ----
if [[ "$OS_ID" == "ubuntu" && "$OS_VER" == "22.04" ]]; then
    e_info "Afegint el repositori de PHP (ppa:ondrej/php)..."
    silenci apt-get $APT install -y software-properties-common || exit 1
    LC_ALL=C.UTF-8 silenci add-apt-repository -y ppa:ondrej/php || exit 1
elif [[ "$OS_ID" == "debian" ]]; then
    e_info "Afegint el repositori de PHP (packages.sury.org)..."
    curl -fsSLo /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg \
        || { e_err "No s'ha pogut baixar la clau del repositori de PHP."; exit 1; }
    echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ ${OS_CODENAME} main" \
        > /etc/apt/sources.list.d/php.list
fi
# Ubuntu 24.04 ja porta PHP 8.3 als repositoris oficials.
silenci apt-get $APT update || exit 1

# ---- Apache + PHP + MariaDB + Redis ----
e_info "Instal·lant Apache, PHP ${PHP_VER}, MariaDB i Redis (pot trigar uns minuts)..."
silenci apt-get $APT install -y \
    apache2 libapache2-mod-php${PHP_VER} \
    php${PHP_VER} php${PHP_VER}-{common,cli,gd,mysql,mbstring,bcmath,xml,curl,zip} \
    mariadb-server redis-server || exit 1

for modul in /etc/apache2/mods-enabled/php*.load; do
    [[ -e "$modul" ]] || continue
    nom=$(basename "$modul" .load)
    [[ "$nom" != "php${PHP_VER}" ]] && a2dismod -q "$nom" >/dev/null 2>&1
done
a2enmod -q php${PHP_VER} rewrite ssl headers >/dev/null 2>&1
update-alternatives --set php /usr/bin/php${PHP_VER} >/dev/null 2>&1
systemctl enable --now mariadb redis-server apache2 >/dev/null 2>&1
e_ok "Apache, PHP ${PHP_VER}, MariaDB i Redis instal·lats."

# ---- Composer ----
if ! command -v composer >/dev/null 2>&1; then
    e_info "Instal·lant Composer..."
    curl -sS https://getcomposer.org/installer \
        | php -- --quiet --install-dir=/usr/local/bin --filename=composer \
        || { e_err "No s'ha pogut instal·lar Composer."; exit 1; }
fi

# ---- Descàrrega del panell ----
e_info "Descarregant l'última versió estable del panell..."
mkdir -p "$PANEL_DIR"
cd "$PANEL_DIR" || exit 1
curl -fsSLo panel.tar.gz https://github.com/pterodactyl/panel/releases/latest/download/panel.tar.gz \
    || { e_err "No s'ha pogut descarregar el panell."; exit 1; }
tar -xzf panel.tar.gz && rm -f panel.tar.gz
chmod -R 755 storage/* bootstrap/cache/

# ---- Base de dades (usuari propi; Pterodactyl NO permet root) ----
e_info "Creant la base de dades..."
DB_PASS=$(genera_pw 32)
mysql -u root <<SQL || { e_err "No s'ha pogut crear la base de dades."; exit 1; }
CREATE DATABASE IF NOT EXISTS ${DB_NAME};
CREATE USER IF NOT EXISTS '${DB_USER}'@'127.0.0.1' IDENTIFIED BY '${DB_PASS}';
ALTER USER '${DB_USER}'@'127.0.0.1' IDENTIFIED BY '${DB_PASS}';
GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'127.0.0.1' WITH GRANT OPTION;
FLUSH PRIVILEGES;
SQL

# ---- VirtualHost d'Apache (primer sense SSL, per validar el certificat) ----
VHOST="/etc/apache2/sites-available/pterodactyl.conf"

vhost_http() {
    cat > "$VHOST" <<EOF
<VirtualHost *:80>
    ServerName ${SUBDOMINIO}
    DocumentRoot "${PANEL_DIR}/public"

    AllowEncodedSlashes On

    php_value upload_max_filesize 100M
    php_value post_max_size 100M

    <Directory "${PANEL_DIR}/public">
        AllowOverride all
        Require all granted
    </Directory>
</VirtualHost>
EOF
}

vhost_https() {
    cat > "$VHOST" <<EOF
<VirtualHost *:80>
    ServerName ${SUBDOMINIO}

    # Deixem passar la validació de Let's Encrypt per http (renovacions).
    Alias /.well-known/acme-challenge/ "${PANEL_DIR}/public/.well-known/acme-challenge/"
    <Directory "${PANEL_DIR}/public/.well-known/acme-challenge/">
        Require all granted
    </Directory>

    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{SERVER_NAME}/\$1 [R,L]
</VirtualHost>

<VirtualHost *:443>
    ServerName ${SUBDOMINIO}
    DocumentRoot "${PANEL_DIR}/public"

    AllowEncodedSlashes On

    php_value upload_max_filesize 100M
    php_value post_max_size 100M

    <Directory "${PANEL_DIR}/public">
        Require all granted
        AllowOverride all
    </Directory>

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/${SUBDOMINIO}/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/${SUBDOMINIO}/privkey.pem
</VirtualHost>
EOF
}

vhost_http
a2dissite -q 000-default >/dev/null 2>&1
a2ensite -q pterodactyl >/dev/null 2>&1
systemctl reload apache2

# 80/443 = panell · 8080 = API de Wings · 2022 = SFTP · resta = jocs
obre_ports 80/tcp 443/tcp 8080/tcp 2022/tcp "${PORTS_JOCS/-/:}/tcp" "${PORTS_JOCS/-/:}/udp"

# ---- Certificat SSL ----
ESQUEMA="http"
if [[ "$usar_ssl" == "si" ]]; then
    e_info "Sol·licitant el certificat SSL de Let's Encrypt..."
    silenci apt-get $APT install -y certbot

    if certbot certonly --webroot -w "${PANEL_DIR}/public" -d "$SUBDOMINIO" \
           --non-interactive --agree-tos -m "$EMAIL_ADMIN" \
           --deploy-hook "systemctl reload apache2; systemctl try-restart wings || true" >/dev/null 2>&1; then
        vhost_https
        systemctl reload apache2
        ESQUEMA="https"
        e_ok "Certificat SSL instal·lat (es renovarà sol)."
    else
        e_warn "No s'ha pogut obtenir el certificat. Continuo SENSE SSL (http)."
        e_warn "Comprova que ${SUBDOMINIO} apunta a aquest servidor i que el port 80 és obert."
    fi
fi
APP_URL="${ESQUEMA}://${SUBDOMINIO}"

# ---- Configuració del panell ----
e_info "Instal·lant les dependències del panell (Composer)..."
cp .env.example .env
COMPOSER_ALLOW_SUPERUSER=1 silenci composer install --no-dev --optimize-autoloader \
    --no-interaction || exit 1
silenci php artisan key:generate --force || exit 1

e_info "Configurant l'entorn del panell..."
silenci php artisan p:environment:setup --no-interaction \
    --author="$EMAIL_ADMIN" --url="$APP_URL" --timezone="Europe/Madrid" \
    --cache=redis --session=redis --queue=redis \
    --redis-host=127.0.0.1 --redis-port=6379 \
    --settings-ui=true --telemetry=0 || exit 1

silenci php artisan p:environment:database --no-interaction \
    --host=127.0.0.1 --port=3306 --database="$DB_NAME" \
    --username="$DB_USER" --password="$DB_PASS" || exit 1

e_info "Creant les taules de la base de dades (pot trigar)..."
silenci php artisan migrate --seed --force || exit 1

# Contrasenya: 8+ caràcters, majúscules, minúscules i almenys un número.
ADMIN_PASS="$(genera_pw 13)Aa1"
silenci php artisan p:user:make --no-interaction \
    --email="$EMAIL_ADMIN" --username=admin \
    --name-first=Admin --name-last=Panell \
    --password="$ADMIN_PASS" --admin=1 || exit 1
e_ok "Panell configurat."

bloqueja_jugadors

# ---- Tasques programades i cua de treball (pteroq) ----
CRON_LINE="* * * * * php ${PANEL_DIR}/artisan schedule:run >> /dev/null 2>&1"
(crontab -l 2>/dev/null | grep -vF "${PANEL_DIR}/artisan schedule:run"; echo "$CRON_LINE") | crontab -

cat > /etc/systemd/system/pteroq.service <<EOF
[Unit]
Description=Pterodactyl Queue Worker
After=redis-server.service

[Service]
User=www-data
Group=www-data
Restart=always
ExecStart=/usr/bin/php ${PANEL_DIR}/artisan queue:work --queue=high,standard,low --sleep=3 --tries=3
StartLimitInterval=180
StartLimitBurst=30
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now pteroq.service >/dev/null 2>&1

# ---- Wings a "P" (primer node) ----
instala_wings
registra_node "$SUBDOMINIO" "$ESQUEMA" "$(ram_mb)" "$(disc_mb)" "$PORTS_JOCS"

configura_wings_local "$NODE_ID"

systemctl enable --now wings >/dev/null 2>&1
sleep 3
if systemctl is-active --quiet wings; then
    e_ok "Wings en marxa a ${SUBDOMINIO}."
else
    e_warn "Wings no ha arrencat. Revisa-ho amb: journalctl -u wings -n 50"
fi

# ---- Credencials ----
APP_KEY=$(grep '^APP_KEY=' "${PANEL_DIR}/.env" | cut -d= -f2-)
{
    echo "Pterodactyl - ${APP_URL}"
    echo "Data: $(date '+%Y-%m-%d %H:%M')"
    echo
    echo "Usuari admin:     admin"
    echo "Email admin:      ${EMAIL_ADMIN}"
    echo "Contrasenya:      ${ADMIN_PASS}"
    echo
    echo "Base de dades:    ${DB_NAME}"
    echo "Usuari BD:        ${DB_USER}@127.0.0.1"
    echo "Contrasenya BD:   ${DB_PASS}"
    echo
    echo "APP_KEY (guarda'l FORA del servidor; sense ell no es poden"
    echo "recuperar les dades xifrades): ${APP_KEY}"
} > "$CREDENCIALS"
chmod 600 "$CREDENCIALS"

echo
echo -e "\e[0;32m(-) LLEST: \e[1;32mPterodactyl instal·lat i configurat.\e[0m"
echo -e "    Panell:      \e[1;33m${APP_URL}\e[0m"
echo -e "    Usuari:      \e[1;33madmin\e[0m"
echo -e "    Contrasenya: \e[1;33m${ADMIN_PASS}\e[0m"
echo -e "    (Totes les credencials són a ${CREDENCIALS} de \"P\".)"
exit 0
REMOTE
)


# =============================================================================
#  CODI REMOT: preparació d'un NODE nou (s'executa al VPS nou)
#  Els missatges van per stderr; per stdout NOMÉS surt "RAM_MB DISC_MB".
# =============================================================================
remote_node_prepara=$(cat <<'REMOTE'
exec 3>&1 1>&2

comprova_sistema
instala_basics
instala_wings

obre_ports 8080/tcp 2022/tcp "${PORTS_JOCS/-/:}/tcp" "${PORTS_JOCS/-/:}/udp"

# Si el panell va per https, el node també ha de tenir certificat (el
# navegador es connecta directament a Wings per wss://).
if [[ "$ESQUEMA" == "https" ]]; then
    if [[ -f "/etc/letsencrypt/live/${NODE_FQDN}/fullchain.pem" ]]; then
        e_info "El certificat de ${NODE_FQDN} ja existia."
    else
        e_info "Sol·licitant el certificat SSL per a \e[0;33m${NODE_FQDN}\e[1;34m..."
        obre_ports 80/tcp
        silenci apt-get $APT install -y certbot || exit 1
        if ! certbot certonly --standalone -d "$NODE_FQDN" \
                 --non-interactive --agree-tos -m "$EMAIL_ADMIN" \
                 --deploy-hook "systemctl try-restart wings || true" >/dev/null 2>&1; then
            e_err "No s'ha pogut obtenir el certificat de ${NODE_FQDN}."
            e_err "Comprova que el DNS apunta a aquest VPS i que el port 80 és lliure i obert."
            exit 1
        fi
        e_ok "Certificat SSL instal·lat (es renovarà sol)."
    fi
fi

echo "$(ram_mb) $(disc_mb)" >&3
exit 0
REMOTE
)


# =============================================================================
#  CODI REMOT: alta del node al PANELL (s'executa a "P")
#  Els missatges van per stderr; per stdout NOMÉS surt el config.yml de Wings.
# =============================================================================
remote_node_alta=$(cat <<'REMOTE'
exec 3>&1 1>&2

if [[ ! -f "${PANEL_DIR}/.env" ]]; then
    e_err "No hi ha cap panell instal·lat a ${PANEL_DIR}."
    exit 1
fi

# Eggs importats després de la instal·lació: també queden bloquejats.
bloqueja_jugadors

registra_node "$NODE_FQDN" "$ESQUEMA" "$RAM_MB" "$DISC_MB" "$PORTS_JOCS"

cd "$PANEL_DIR" || exit 1
php artisan p:node:configuration "$NODE_ID" --format=yaml >&3 \
    || { e_err "No s'ha pogut generar la configuració de Wings."; exit 1; }
exit 0
REMOTE
)


# =============================================================================
#  EXECUCIÓ
# =============================================================================
clear

if [[ -z "$nodo" ]]; then
    # -------------------------------------------------------------------------
    #  MODE PANELL
    # -------------------------------------------------------------------------
    asegura_clau "$subdominio"

    preambul=$(printf 'OMITIR_SSL=%q\nSUBDOMINIO=%q\nEMAIL_ADMIN=%q\nPORTS_JOCS=%q\n' \
                      "$nossl" "$subdominio" "$email_admin" "$ports_jocs")

    ssh "${SSH_OPTS[@]}" "$usuario@$subdominio" "bash -s" <<< "${preambul}
${remote_comuns}
${remote_panell}"
    exit $?
fi

# -----------------------------------------------------------------------------
#  MODE NODE
# -----------------------------------------------------------------------------
info "Afegint el node \e[0;33m${nodo}\e[1;36m al panell \e[0;33m${subdominio}\e[1;36m."

asegura_clau "$subdominio"
asegura_clau "$nodo"

# 1) El node fa servir el mateix esquema (http/https) que el panell.
esquema=$(ssh "${SSH_OPTS[@]}" "$usuario@$subdominio" \
          "grep -m1 '^APP_URL=' /var/www/pterodactyl/.env 2>/dev/null" \
          | cut -d= -f2- | tr -d '"' | cut -d: -f1)
if [[ "$esquema" != "http" && "$esquema" != "https" ]]; then
    err "No s'ha trobat cap panell instal·lat a \e[0;33m${subdominio}\e[1;31m."
    err "Instal·la'l primer: ./$(basename "$0") -s ${subdominio}"
    exit 1
fi
info "El panell fa servir \e[0;33m${esquema}\e[1;36m; el node també."

preambul=$(printf 'NODE_FQDN=%q\nESQUEMA=%q\nEMAIL_ADMIN=%q\nPORTS_JOCS=%q\n' \
                  "$nodo" "$esquema" "$email_admin" "$ports_jocs")

# 2) Preparem el VPS nou (Docker, Wings, certificat, tallafoc).
info "Preparant \e[0;33m${nodo}\e[1;36m (Docker, Wings i certificat)..."
recursos=$(ssh "${SSH_OPTS[@]}" "$usuario@$nodo" "bash -s" <<< "${preambul}
${remote_comuns}
${remote_node_prepara}") || { err "Ha fallat la preparació de ${nodo}."; exit 1; }

read -r ram_mb disc_mb <<< "$(echo "$recursos" | tail -n1)"
if [[ ! "$ram_mb" =~ ^[0-9]+$ || ! "$disc_mb" =~ ^[0-9]+$ ]]; then
    err "No s'han pogut llegir els recursos de ${nodo}."
    exit 1
fi
ok "${nodo} preparat (${ram_mb} MB RAM, ${disc_mb} MB disc)."

# 3) Donem d'alta el node al panell i n'obtenim el config.yml.
info "Donant d'alta el node al panell..."
preambul+=$(printf '\nRAM_MB=%q\nDISC_MB=%q\n' "$ram_mb" "$disc_mb")
config_yml=$(ssh "${SSH_OPTS[@]}" "$usuario@$subdominio" "bash -s" <<< "${preambul}
${remote_comuns}
${remote_node_alta}") || { err "Ha fallat l'alta del node al panell."; exit 1; }

if ! grep -q "^token:" <<< "$config_yml"; then
    err "La configuració rebuda del panell no és vàlida."
    exit 1
fi

# Consola: Wings del node ha d'acceptar connexions que vénen del panell.
config_yml=$(posa_origens "$subdominio" <<< "$config_yml")
ok "Consola: orígens permesos a Wings (https/http://${subdominio})."

# 4) Enviem la configuració al node i arrenquem Wings.
info "Connectant Wings de \e[0;33m${nodo}\e[1;36m amb el panell..."
if ssh "${SSH_OPTS[@]}" "$usuario@$nodo" \
       "umask 077 && cat > /etc/pterodactyl/config.yml && systemctl enable wings >/dev/null 2>&1 && systemctl restart wings && sleep 3 && systemctl is-active --quiet wings" \
       <<< "$config_yml"; then
    echo
    echo -e "\e[0;32m(-) LLEST: \e[1;32mNode \e[0;33m${nodo}\e[1;32m afegit i connectat al panell.\e[0m"
    echo -e "    Ports de joc: \e[1;33m${ports_jocs}\e[0m"
    echo -e "    Comprova-ho a: \e[1;33m${esquema}://${subdominio}/admin/nodes\e[0m (cor en verd)."
else
    warn "Wings no ha arrencat a ${nodo}. Revisa-ho allà amb: journalctl -u wings -n 50"
    exit 1
fi