#!/bin/bash

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

# Collect user input
read -p "Enter your domain (e.g., usnode1.xorbit.link): " DOMAIN
check_error "Domain cannot be empty"

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

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

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

# 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
echo 'export PATH=$PATH:/usr/local/go/bin' >> /etc/profile
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 Caddyfile directory
mkdir -p /etc/caddy
check_error "Failed to create /etc/caddy directory"

# 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"

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