#!/bin/bash

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 Wings Installer for Debian 12 by VS-Shop      ${NC}"
    echo -e ${LIGHT_BLUE}"=================================================================${NC}"
    echo -e "${YELLOW}This installation script requires a clean installation of Debian 12 (Bookworm).${NC}"
    echo -e "${YELLOW}Please confirm you are running it on a fresh system.${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

WINGS_DOMAIN=$(prompt "Enter the domain name you want to use for Wings (e.g., wings.example.com). Leave blank if not using a public domain for Wings." "")
if [ -n "$WINGS_DOMAIN" ]; then
    ADMIN_EMAIL=$(prompt "Enter an email address for Certbot to use for Wings (for urgent renewal notices and security advisories)" "me@anthony-morales.online") # Corrected default email
fi

echo -e "${GREEN}Updating system and installing dependencies...${NC}"
apt update && apt upgrade -y
apt install -y curl sudo gnupg lsb-release ca-certificates

echo -e "${GREEN}Installing Docker (from official source)...${NC}"
if ! command -v docker &> /dev/null; then
    curl -fsSL https://get.docker.com | bash
else
    echo -e "${YELLOW}Docker appears to be already installed. Skipping Docker installation.${NC}"
fi

echo -e "${GREEN}Enabling Docker...${NC}"
systemctl enable --now docker

echo -e "${GREEN}Installing Wings...${NC}"
mkdir -p /etc/pterodactyl
ARCH=$(uname -m)
ARCH_TYPE=$([[ "$ARCH" == "x86_64" ]] && echo "amd64" || echo "arm64")

curl -L -o /usr/local/bin/wings "https://github.com/pterodactyl/wings/releases/latest/download/wings_linux_${ARCH_TYPE}"
chmod +x /usr/local/bin/wings

echo -e "${GREEN}Creating systemd service file for Wings...${NC}"
cat > /etc/systemd/system/wings.service <<EOF
[Unit]
Description=Pterodactyl Wings Daemon
After=docker.service
Requires=docker.service

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

[Install]
WantedBy=multi-user.target
EOF

echo -e "${GREEN}Enabling Wings service...${NC}"
systemctl enable --now wings

if [ -n "$WINGS_DOMAIN" ]; then
    echo -e "${GREEN}Installing Certbot...${NC}"
    apt install -y certbot

    WEB_SERVICE=""
    if systemctl is-active --quiet nginx; then
        WEB_SERVICE="nginx"
    elif systemctl is-active --quiet apache2; then
        WEB_SERVICE="apache2"
    fi

    if [ -n "$WEB_SERVICE" ]; then
        echo -e "${YELLOW}Stopping $WEB_SERVICE temporarily to free up port 80 for Certbot...${NC}"
        systemctl stop "$WEB_SERVICE"
    else
        echo -e "${YELLOW}No common web server (Nginx/Apache) found running on port 80. Proceeding with Certbot standalone.${NC}"
    fi

    echo -e "${GREEN}Stopping Wings temporarily for Certbot standalone validation...${NC}"
    systemctl stop wings || true

    echo -e "${GREEN}Obtaining SSL certificate for Wings domain using Certbot's standalone authenticator...${NC}"
    certbot certonly --standalone --agree-tos --email "$ADMIN_EMAIL" -d "$WINGS_DOMAIN" --force-renewal

    CERTBOT_STATUS=$?

    if [ -n "$WEB_SERVICE" ]; then
        echo -e "${YELLOW}Starting $WEB_SERVICE back up...${NC}"
        systemctl start "$WEB_SERVICE"
    fi

    echo -e "${GREEN}Restarting Wings service...${NC}"
    systemctl start wings

    if [ $CERTBOT_STATUS -eq 0 ]; then
        echo -e "${GREEN}SSL certificate for Wings domain obtained successfully!${NC}"
        echo -e "${YELLOW}IMPORTANT: You must manually update your /etc/pterodactyl/config.yml to use these SSL certificates.${NC}"
        echo -e "${YELLOW}  Certificate Path: /etc/letsencrypt/live/$WINGS_DOMAIN/fullchain.pem${NC}"
        echo -e "${YELLOW}  Key Path:         /etc/letsencrypt/live/$WINGS_DOMAIN/privkey.pem${NC}"
        echo -e "${YELLOW}  Ensure 'api.listen_address' is set to use HTTPS (e.g., 0.0.0.0:8443) in config.yml.${NC}"
        echo -e "${YELLOW}  After updating config.yml, restart Wings: systemctl restart wings${NC}"
    else
        echo -e "${RED}Failed to obtain SSL certificate for Wings domain (Certbot exit code: $CERTBOT_STATUS). Please check your DNS and ensure port 80 is open and not in use by any unexpected process.${NC}"
        echo -e "${RED}Wings will proceed without a Let's Encrypt certificate for the domain. You will need to configure SSL manually later if desired.${NC}"
    fi
else
    echo -e "${YELLOW}No domain provided for Wings. Skipping Certbot installation for Wings.${NC}"
fi

confirm_wings_configuration() {
    echo -e ${LIGHT_BLUE}"=================================================================${NC}"
    echo -e ${LIGHT_BLUE}"           Pterodactyl Wings Configuration Reminder          ${NC}"
    echo -e ${LIGHT_BLUE}"=================================================================${NC}"
    echo -e "${YELLOW}1. Open a new terminal and connect to this server.${NC}"
    echo -e "${YELLOW}2. Log in to your Pterodactyl Panel and create a Location and a Node.${NC}"
    echo -e "${YELLOW}3. Navigate to Nodes > Your Node > Configuration tab.${NC}"
    echo -e "${YELLOW}4. Download or copy the config and paste it to: /etc/pterodactyl/config.yml${NC}"
    if [ -n "$WINGS_DOMAIN" ]; then
        echo -e "${YELLOW}5. IMPORTANT: Since you obtained a Let's Encrypt SSL certificate for Wings,${NC}"
        echo -e "${YELLOW}   you MUST edit the /etc/pterodactyl/config.yml file. Find the 'api' section${NC}"
        echo -e "${YELLOW}   and update 'certificate' and 'key' paths to point to the Let's Encrypt certificates:${NC}"
        echo -e "${YELLOW}     certificate: /etc/letsencrypt/live/$WINGS_DOMAIN/fullchain.pem${NC}"
        echo -e "${YELLOW}     key: /etc/letsencrypt/live/$WINGS_DOMAIN/privkey.pem${NC}"
        echo -e "${YELLOW}6. Save the config.yml file. Then, run 'systemctl restart wings'.${NC}"
        echo -e "${YELLOW}7. Come back to this window to continue.${NC}"
    else
        echo -e "${YELLOW}5. Save and come back to this window to continue.${NC}"
    fi
    echo -e ${LIGHT_BLUE}"=================================================================${NC}"

    while true; do
        read -p "Have you completed the Node Configuration and any necessary SSL updates for Wings? (Y/N): " response
        case $response in
            [Yy]* ) break;;
            [Nn]* ) echo -e "${RED}Please complete the Node Configuration and run the script again.${NC}"; exit;;
            * ) echo -e "${RED}Please answer with 'Y' (Yes) or 'N' (No).${NC}";;
        esac
    done
}

confirm_wings_configuration

echo -e "${GREEN}Pterodactyl Wings Configuration completed successfully!${NC}"
echo -e "${GREEN}Pterodactyl Wings is now installed and running on Debian 12.${NC}"
