#!/bin/bash

# Function to check if command succeeded
check_error() {
    if [ $? -ne 0 ]; then
        echo "Error: $1"
        exit 1
    fi
}

# Check if script is run as root
if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root (with sudo)"
    exit 1
fi

# Check for required commands
if ! command -v wget &> /dev/null; then
    echo "wget is required but not installed. Installing..."
    apt-get update && apt-get install -y wget
    check_error "Failed to install wget"
fi

# Check if port 8443 is available
if netstat -tuln | grep -q ':8443 '; then
    echo "Error: Port 8443 is already in use"
    exit 1
fi

# Collect user input
while true; do
    read -p "Enter your domain (e.g., usnode1.xorbit.link): " DOMAIN
    if [[ $DOMAIN =~ ^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
        break
    else
        echo "Invalid domain format. Please try again."
    fi
done

# Generate email automatically
EMAIL="example@${DOMAIN}"

read -p "Enter desired username for proxy: " PROXY_USER
check_error "Username cannot be empty"

read -s -p "Enter desired password for proxy: " PROXY_PASS
echo
check_error "Password cannot be empty"

# Create temporary directory for downloads
TEMP_DIR=$(mktemp -d)
cd "$TEMP_DIR" || exit 1

# Install Go 1.22
echo "Installing Go 1.22..."
wget https://go.dev/dl/go1.22.0.linux-amd64.tar.gz
check_error "Failed to download Go"

rm -rf /usr/local/go
tar -C /usr/local -xzf go1.22.0.linux-amd64.tar.gz
check_error "Failed to extract Go"

# Add Go to PATH if not already added
if ! grep -q "/usr/local/go/bin" /etc/profile; then
    echo 'export PATH=$PATH:/usr/local/go/bin' >> /etc/profile
fi
source /etc/profile

# Install xcaddy and build caddy with forwardproxy
echo "Building Caddy with forwardproxy..."
go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
check_error "Failed to install xcaddy"

~/go/bin/xcaddy build --with github.com/caddyserver/forwardproxy=github.com/klzgrad/forwardproxy@naive
check_error "Failed to build Caddy"

# Copy caddy to /usr/bin
cp caddy /usr/bin/
chmod +x /usr/bin/caddy
check_error "Failed to install Caddy"

# Create service file
echo "Creating service file..."
cat > /etc/systemd/system/naive.service << EOL
[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target

[Service]
Type=notify
User=root
Group=root
ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
EOL

# Create required directories
mkdir -p /etc/caddy /var/www/html
check_error "Failed to create required directories"

# Create Caddyfile with user input
cat > /etc/caddy/Caddyfile << EOL
{
        https_port 8443
}
:8443, ${DOMAIN}
tls ${EMAIL}
route {
        forward_proxy {
                basic_auth ${PROXY_USER} ${PROXY_PASS}
                hide_ip
                hide_via
                probe_resistance
        }
        file_server {
                root /var/www/html
        }
}
EOL

# Start and enable service
echo "Starting naive proxy service..."
systemctl daemon-reload
systemctl enable naive
systemctl start naive
check_error "Failed to start naive service"

# Cleanup
cd - || exit 1
rm -rf "$TEMP_DIR"

echo "NaiveProxy deployment completed successfully!"
echo "Your proxy is available at: ${DOMAIN}:8443"
echo "Username: ${PROXY_USER}"
echo "Password: ${PROXY_PASS}"

# Check if service is running
if systemctl is-active --quiet naive; then
    echo "Service is running properly"
else
    echo "Warning: Service is not running. Please check logs with: journalctl -u naive"
fi 