#!/bin/bash

# Default the TZ environment variable to UTC.
TZ=${TZ:-UTC}
export TZ

# Switch to the container's working directory
cd /home/container || exit 1

# Couleurs
RED='\033[0;31m'
DARK_BLUE='\033[0;34m'
YELLOW='\033[0;33m'
NC='\033[0m'

# ---------------------------------------------------------------------------
# Environnement Node : tout vit dans /home/container (le volume Pterodactyl)
#   - node_modules : modules du projet (npm install)
#   - .npm         : cache npm (tarballs, logs)
#   - .npm-global  : cible de "npm install -g" (/usr/local n'est pas inscriptible)
#   - .tmp         : espace de travail de npm / node-gyp et du bot (TMPDIR).
#                    /tmp est un tmpfs de 100 Mo monté par Wings : trop petit
#                    pour les gros packages et hors quota disque du serveur.
# ---------------------------------------------------------------------------
TMPDIR="/home/container/.tmp"
NPM_GLOBAL_DIR="/home/container/.npm-global"
INSTALL_LOCK="/home/container/.npm/install.lock"
export TMPDIR
export npm_config_cache="/home/container/.npm"
export npm_config_prefix="$NPM_GLOBAL_DIR"
export npm_config_update_notifier=false
export PATH="$NPM_GLOBAL_DIR/bin:/home/container/node_modules/.bin:$PATH"

mkdir -p "$TMPDIR" "$npm_config_cache" "$NPM_GLOBAL_DIR/bin"
# Nettoie les résidus d'une install interrompue (kill/restart en plein npm)
find "$TMPDIR" -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null

# Fichier combiné des certificats CA (Node ne lit pas /etc/ssl par défaut)
cat /usr/local/share/ca-certificates/KataCAold.crt \
    /usr/local/share/ca-certificates/KataCA.crt \
    > "$TMPDIR/combined-ca.crt" 2> /dev/null
export NODE_EXTRA_CA_CERTS="$TMPDIR/combined-ca.crt"

# Paramètres pour la vérification des fichiers
MAX_FILES=${MAX_FILES:-500000}    # Limite par défaut : 100 fichiers + dossiers
VOLUME_PATH=${VOLUME_PATH:-/home/container}  # Chemin par défaut
CHECK_INTERVAL=${CHECK_INTERVAL:-15}  # Vérification toutes les 15 seconde

# Chemin vers le fichier BOT_JS_FILE
FILE_PATH="/home/container/${BOT_JS_FILE}"

# Vérification initiale du nombre de fichiers et dossiers
FILE_COUNT=$(find "$VOLUME_PATH" \( -type f -o -type d \) | wc -l)
if [ "$FILE_COUNT" -ge "$MAX_FILES" ]; then
    echo -e "${RED}[ERROR] Maximum file/folder limit exceeded at startup (please delete files to continue). Container shutdown...${NC}"
    exit 1  # Arrête le conteneur immédiatement
fi

# Afficher la version de Node.js en bleu foncé
echo -e "${DARK_BLUE}[INFO] Node.js version: $(node -v) (npm $(npm -v))${NC}"

# Vérifie si le fichier BOT_JS_FILE existe
if [ ! -f "$FILE_PATH" ]; then
    echo -e "${RED}[ERROR] Your ${BOT_JS_FILE} file was not found. You can change this value in the \"Startup\" tab.${NC}"
    exit 1
fi

# Lance "npm install" sous verrou : deux installs simultanées sur le même
# node_modules (bot qui relance npm, restart pendant l'install) se corrompent
# mutuellement. Le résultat de npm est affiché et son code de retour propagé.
# --no-audit/--no-fund : moins de bruit et deux requêtes réseau de moins par boot.
npm_install() {
    flock -w 600 "$INSTALL_LOCK" \
        npm install --no-audit --no-fund --no-progress "$@"
}

# Vérification des modules dans package.json si le fichier existe
if [ -f "/home/container/package.json" ]; then
    echo -e "${DARK_BLUE}[INFO] Checking package.json modules...${NC}"
    if npm_install; then
        echo -e "${DARK_BLUE}[INFO] All modules are up to date.${NC}"
    else
        echo -e "${RED}[ERROR] Some modules from package.json could not be installed (see above). The bot may fail to start.${NC}"
    fi
else
    echo -e "${RED}[ERROR] The package.json file is missing. Hosting launches without installing any modules.${NC}"
fi

# Installation des modules spécifiés dans NODE_PACKAGES si défini
if [ -n "${NODE_PACKAGES}" ]; then
    echo -e "${DARK_BLUE}[INFO] Installation of the modules listed in \"Startup\"${NC}"
    if npm_install ${NODE_PACKAGES}; then
        echo -e "${DARK_BLUE}[INFO] Modules successfully installed.${NC}"
    else
        echo -e "${RED}[ERROR] Some modules from \"Startup\" could not be installed (see above).${NC}"
    fi
fi

# Logo en "orange" (jaune) avant toute autre commande
echo -e "${YELLOW}    __ __      __        ____                      "
echo -e "   / //_/___ _/ /_____ _/ __ )__  ______ ___  ____ "
echo -e "  / ,< / __ \`/ __/ __ \`/ __  / / / / __ \`__ \\/ __ \\"
echo -e " / /| / /_/ / /_/ /_/ / /_/ / /_/ / / / / / / /_/ /"
echo -e "/_/ |_\\__,_/\\__/\\__,_/_____/\\__,_/_/ /_/ /_/ .___/ "
echo -e "                                          /_/      ${NC}"

# Fonction de surveillance des fichiers et dossiers
monitor_files() {
    local PREV_COUNT=0
    local RATE_THRESHOLD=5000  # Seuil de nouveaux fichiers par intervalle (ajustable)
    local BURST_COUNT=0        # Compteur de "pics" consécutifs
    local MAX_BURST=2          # Nombre max de pics avant arrêt

    while true; do
        FILE_COUNT=$(find "$VOLUME_PATH" \( -type f -o -type d \) | wc -l)
        
        # Vérification de la limite absolue
        if [ "$FILE_COUNT" -ge "$MAX_FILES" ]; then
            echo -e "${RED}[ERROR] Maximum file/folder limit exceeded ($FILE_COUNT >= $MAX_FILES). Container forced to stop...${NC}"
            if [ -f "/tmp/main_pid" ]; then
                MAIN_PID=$(cat /tmp/main_pid)
                kill -KILL "$MAIN_PID"
            fi
            exit 0
        fi

        # Vérification du taux de création avec tolérance pour bursts légitimes
        if [ "$PREV_COUNT" -ne 0 ]; then
            RATE=$((FILE_COUNT - PREV_COUNT))
            if [ "$RATE" -gt "$RATE_THRESHOLD" ]; then
                BURST_COUNT=$((BURST_COUNT + 1))
                echo -e "${YELLOW}[WARNING] High file creation rate detected ($RATE new files in $CHECK_INTERVAL seconds). Burst count: $BURST_COUNT${NC}"
                if [ "$BURST_COUNT" -ge "$MAX_BURST" ]; then
                    echo -e "${RED}[ERROR] Too many consecutive high file creation bursts ($BURST_COUNT >= $MAX_BURST). Container forced to stop...${NC}"
                    if [ -f "/tmp/main_pid" ]; then
                        MAIN_PID=$(cat /tmp/main_pid)
                        kill -KILL "$MAIN_PID"
                    fi
                    exit 0
                fi
            else
                BURST_COUNT=0  # Réinitialise si le taux redevient normal
            fi
        fi

        PREV_COUNT="$FILE_COUNT"
        sleep "$CHECK_INTERVAL"
    done
}

# Lancement de la surveillance en arrière-plan
monitor_files &

# Convert all of the "{{VARIABLE}}" parts of the command into the expected shell
# variable format of "${VARIABLE}" before evaluating the string and automatically
# replacing the values.
PARSED=$(echo "${STARTUP}" | sed -e 's/{{/${/g' -e 's/}}/}/g' | eval echo "$(cat -)")

# Display the command we're running in the output
printf "\033[1m\033[33mcontainer@pterodactyl~ \033[0m%s\n" "$PARSED"

# Lance la commande principale en arrière-plan et stocke son PID dans /tmp
env ${PARSED} &
MAIN_PID=$!
echo $MAIN_PID > /tmp/main_pid

# Attends que le processus principal se termine
wait $MAIN_PID
EXIT_CODE=$?

# Nettoie le fichier PID
rm -f /tmp/main_pid

# Sort avec le code de sortie du processus principal
exit $EXIT_CODE