#!/bin/bash
# Pterodactyl Installer for Debian 12
# © 2026 Anthony Morales / VS-Shop
# Free to use and distribute with attribution

set -e

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

prompt() {
    local PROMPT_MESSAGE=$1
    local DEFAULT_VALUE=$2
    read -p "$PROMPT_MESSAGE [$DEFAULT_VALUE]: " INPUT
    echo "${INPUT:-$DEFAULT_VALUE}"
}

confirm_clean_install() {
    echo -e ${LIGHT_BLUE}"=================================================================${NC}"
    echo -e ${LIGHT_BLUE}"              Pterodactyl Panel Installer for Debian 12 by VS-Shop${NC}"
    echo -e ${LIGHT_BLUE}"=================================================================${NC}"
    echo -e "${YELLOW}This script is built for a clean installation of Debian 12 (Bookworm).${NC}"
    echo -e "${YELLOW}Please confirm your system matches this requirement.${NC}"
    echo -e ${LIGHT_BLUE}"=================================================================${NC}"
    
    while true; do
        read -p "Is this a clean installation of Debian 12? (Y/N): " response
        case $response in
            [Yy]* ) break;;
            [Nn]* ) echo -e "${RED}Please reinstall Debian 12 and run the script again.${NC}"; exit;;
            * ) echo -e "${RED}Please answer with 'Y' (Yes) or 'N' (No).${NC}";;
        esac
    done
}

confirm_clean_install

DOMAIN=$(prompt "Enter the domain name you want to use for the Pterodactyl panel (e.g., panel.example.com)" "panel.example.com")

echo -e "${GREEN}Updating system and installing base dependencies...${NC}"
apt update
apt -y install curl gnupg apt-transport-https ca-certificates lsb-release software-properties-common sudo unzip git tar cron

echo -e "${GREEN}Installing PHP 8.3 and required extensions...${NC}"
# Add SURY PHP repository
echo "deb https://packages.sury.org/php/ $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/sury-php.list
curl -fsSL https://packages.sury.org/php/apt.gpg | gpg --dearmor -o /etc/apt/trusted.gpg.d/sury-php.gpg

apt update
apt -y install php8.3 php8.3-{cli,common,gd,mysql,mbstring,bcmath,xml,fpm,curl,zip}

echo -e "${GREEN}Installing MariaDB, NGINX, Redis...${NC}"
apt -y install mariadb-server nginx redis-server

echo -e "${GREEN}Installing Composer...${NC}"
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

echo -e "${GREEN}Creating Pterodactyl installation directory...${NC}"
mkdir -p /var/www/pterodactyl
cd /var/www/pterodactyl

echo -e "${GREEN}Downloading Pterodactyl panel...${NC}"
curl -Lo panel.tar.gz https://github.com/pterodactyl/panel/releases/latest/download/panel.tar.gz
tar -xzvf panel.tar.gz
chmod -R 755 storage/* bootstrap/cache/

echo -e "${GREEN}Setting up the MySQL database for Pterodactyl...${NC}"
DB_USER=$(prompt "Enter the MySQL user for Pterodactyl" "pterodactyl")
DB_PASSWORD=$(prompt "Enter the MySQL password for $DB_USER" "yourPassword")
DB_NAME=$(prompt "Enter the database name for Pterodactyl" "panel")

mysql -u root <<MYSQL_SCRIPT
CREATE USER '${DB_USER}'@'127.0.0.1' IDENTIFIED BY '${DB_PASSWORD}';
CREATE DATABASE ${DB_NAME};
GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'127.0.0.1' WITH GRANT OPTION;
FLUSH PRIVILEGES;
MYSQL_SCRIPT

echo -e "${GREEN}Installing Composer dependencies...${NC}"
cp .env.example .env
COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --optimize-autoloader

echo -e "${GREEN}Generating application key...${NC}"
php artisan key:generate --force

echo -e "${GREEN}Running environment setup...${NC}"
php artisan p:environment:setup

echo -e "${GREEN}Running database setup...${NC}"
php artisan p:environment:database

echo -e "${GREEN}Setting up mail environment...${NC}"
php artisan p:environment:mail

echo -e "${GREEN}Migrating and seeding database...${NC}"
php artisan migrate --seed --force

echo -e "${GREEN}Creating Pterodactyl admin user...${NC}"
php artisan p:user:make

echo -e "${GREEN}Setting ownership of Pterodactyl files...${NC}"
chown -R www-data:www-data /var/www/pterodactyl/*

echo -e "${GREEN}Setting up cron job for schedule...${NC}"
(crontab -l ; echo "* * * * * php /home/admin//pterodactyl/artisan schedule:run >> /dev/null 2>&1") | crontab -

echo -e "${GREEN}Creating systemd service for queue worker...${NC}"
cat <<EOF | tee /etc/systemd/system/pteroq.service
[Unit]
Description=Pterodactyl Queue Worker
After=redis-server.service

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

[Install]
WantedBy=multi-user.target
EOF

systemctl enable --now redis-server
systemctl enable --now pteroq.service

echo -e "${GREEN}Creating Nginx configuration...${NC}"
cat > /etc/nginx/sites-available/pterodactyl.conf <<EOF
server {
    listen 80;
    server_name $DOMAIN;

    root /var/www/pterodactyl/public;
    index index.html index.htm index.php;
    charset utf-8;

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

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/pterodactyl.app-error.log error;

    client_max_body_size 100m;
    client_body_timeout 120s;

    sendfile off;

    location ~ \.php\$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)\$;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param PHP_VALUE "upload_max_filesize = 100M \n post_max_size=100M";
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_param HTTP_PROXY "";
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF

ln -s /etc/nginx/sites-available/pterodactyl.conf /etc/nginx/sites-enabled/pterodactyl.conf
systemctl restart nginx

echo -e "${GREEN}Pterodactyl Installation complete on Debian!${NC}"
echo -e "${LIGHT_BLUE}Visit: http://$DOMAIN to begin setup.${NC}"
