#!/bin/bash

set -e

GREEN='\033[0;32m'
AQUA='\033[0;36m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${AQUA}Welcome to VS-Shop PufferPanel Installer 2.0! You are about to install PufferPanel on a fresh OS system."
echo -e "Let's get started with the installation process...${NC}"

read -p "Press [Enter] to continue or [Ctrl+C] to exit."

echo -e "${AQUA}Please enter your domain name for SSL configuration (e.g., panel.example.com):${NC}"
read DOMAIN

echo -e "${AQUA}Updating system packages...${NC}"
sudo apt-get update && sudo apt-get upgrade -y

echo -e "${AQUA}Installing curl...${NC}"
sudo apt-get install -y curl

echo -e "${AQUA}Adding PufferPanel repository...${NC}"
curl -s https://packagecloud.io/install/repositories/pufferpanel/pufferpanel/script.deb.sh | sudo bash

echo -e "${AQUA}Installing PufferPanel...${NC}"
sudo apt-get install -y pufferpanel

echo -e "${AQUA}Adding PufferPanel user...${NC}"
sudo pufferpanel user add

echo -e "${AQUA}Enabling and starting PufferPanel service...${NC}"
sudo systemctl enable --now pufferpanel

echo -e "${AQUA}Installing Nginx...${NC}"
sudo apt-get install -y nginx

echo -e "${AQUA}Configuring Nginx for your domain...${NC}"
cat > /etc/nginx/sites-enabled/pufferpanel.conf <<EOF
server {
    listen 80;
    root /var/www/pufferpanel;

    server_name $DOMAIN;

    location ~ ^/\.well-known {
        root /var/www/html;
        allow all;
    }

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Nginx-Proxy true;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host \$host;
        client_max_body_size 100M;
    }
}
EOF

echo -e "${AQUA}Restarting Nginx...${NC}"
sudo systemctl restart nginx

echo -e "${AQUA}Installing Certbot and Python3 Certbot Nginx plugin...${NC}"
sudo apt-get install -y certbot python3-certbot-nginx

echo -e "${AQUA}Obtaining SSL certificate for domain: $DOMAIN...${NC}"
sudo certbot --nginx -d "$DOMAIN"

echo -e "${GREEN}PufferPanel installation and SSL configuration complete!${NC}"
echo -e "${GREEN}You can now access your PufferPanel at https://$DOMAIN${NC}"
