#!/bin/bash

DOMAIN="$1"
PROXY_PORT=""

# Parse optional --proxy PORT argument
shift
while [[ $# -gt 0 ]]; do
    case "$1" in
        --proxy)
            PROXY_PORT="$2"
            shift 2
            ;;
        *)
            echo "Unknown argument: $1"
            exit 1
            ;;
    esac
done

WEBROOT="/var/www/html/html/$DOMAIN"
APACHE_CONF="/etc/apache2/sites-available/$DOMAIN.conf"

if [ -z "$DOMAIN" ]; then
    echo "Usage: $0 example.com [--proxy PORT]"
    echo "  example.com           Create a standard website"
    echo "  example.com --proxy 3000  Create a reverse proxy to localhost:3000 with SSL"
    exit 1
fi

# Count dots in domain
DOT_COUNT=$(grep -o "\." <<< "$DOMAIN" | wc -l)

# Only add www. if domain has exactly 1 dot (example.com)
if [ "$DOT_COUNT" -eq 1 ]; then
    WWW_DOMAIN="www.$DOMAIN"
else
    WWW_DOMAIN=""
fi

echo ">>> Creating Apache config at $APACHE_CONF"

if [ -n "$PROXY_PORT" ]; then
    # ── PROXY MODE ────────────────────────────────────────────────────────────
    echo ">>> Proxy mode: forwarding $DOMAIN → http://localhost:$PROXY_PORT"

    # Step 1: write HTTP-only vhost so Certbot can complete its ACME challenge
    sudo bash -c "cat > $APACHE_CONF" <<EOF
<VirtualHost *:80>
    ServerName $DOMAIN
EOF

    if [ -n "$WWW_DOMAIN" ]; then
    sudo bash -c "cat >> $APACHE_CONF" <<EOF
    ServerAlias $WWW_DOMAIN
EOF
    fi

    sudo bash -c "cat >> $APACHE_CONF" <<EOF

    ErrorLog \${APACHE_LOG_DIR}/$DOMAIN-error.log
    CustomLog \${APACHE_LOG_DIR}/$DOMAIN-access.log combined
</VirtualHost>
EOF

    echo ">>> Enabling proxy modules"
    sudo a2enmod proxy proxy_http rewrite ssl headers

    echo ">>> Enabling site"
    sudo a2ensite "$DOMAIN.conf"

    echo ">>> Reloading Apache"
    sudo systemctl reload apache2

    # Step 2: obtain certificate only (certonly) — does not touch SSL vhosts
    echo ">>> Running Certbot (certonly)"
    CERT_ARGS=(-d "$DOMAIN")
    [ -n "$WWW_DOMAIN" ] && CERT_ARGS+=(-d "$WWW_DOMAIN")
    sudo certbot certonly --apache "${CERT_ARGS[@]}" --non-interactive --agree-tos -m admin@$DOMAIN

    CERT_DIR="/etc/letsencrypt/live/$DOMAIN"

    # Step 3: rewrite config with full HTTP→HTTPS redirect + SSL proxy vhost
    sudo bash -c "cat > $APACHE_CONF" <<EOF
<VirtualHost *:80>
    ServerName $DOMAIN
EOF

    if [ -n "$WWW_DOMAIN" ]; then
    sudo bash -c "cat >> $APACHE_CONF" <<EOF
    ServerAlias $WWW_DOMAIN
EOF
    fi

    sudo bash -c "cat >> $APACHE_CONF" <<EOF

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    ErrorLog \${APACHE_LOG_DIR}/$DOMAIN-error.log
    CustomLog \${APACHE_LOG_DIR}/$DOMAIN-access.log combined
</VirtualHost>

<VirtualHost *:443>
    ServerName $DOMAIN
EOF

    if [ -n "$WWW_DOMAIN" ]; then
    sudo bash -c "cat >> $APACHE_CONF" <<EOF
    ServerAlias $WWW_DOMAIN
EOF
    fi

    sudo bash -c "cat >> $APACHE_CONF" <<EOF

    SSLEngine on
    SSLCertificateFile    $CERT_DIR/fullchain.pem
    SSLCertificateKeyFile $CERT_DIR/privkey.pem

    ProxyPreserveHost On
    ProxyPass        / http://localhost:$PROXY_PORT/
    ProxyPassReverse / http://localhost:$PROXY_PORT/

    # Forward real client IP
    RequestHeader set X-Forwarded-Proto "https"
    RequestHeader set X-Forwarded-For   "%{REMOTE_ADDR}e"

    ErrorLog \${APACHE_LOG_DIR}/$DOMAIN-error.log
    CustomLog \${APACHE_LOG_DIR}/$DOMAIN-access.log combined
</VirtualHost>
EOF

else
    # ── STANDARD SITE MODE ───────────────────────────────────────────────────
    echo ">>> Creating web root at $WEBROOT"
    sudo mkdir -p "$WEBROOT"
    sudo chown -R $USER:$USER "$WEBROOT"

    echo ">>> Creating sample index page"
    echo "<h1>$DOMAIN is live!</h1>" | sudo tee "$WEBROOT/index.html"

    sudo bash -c "cat > $APACHE_CONF" <<EOF
<VirtualHost *:80>
    ServerName $DOMAIN
EOF

    if [ -n "$WWW_DOMAIN" ]; then
    sudo bash -c "cat >> $APACHE_CONF" <<EOF
    ServerAlias $WWW_DOMAIN
EOF
    fi

    sudo bash -c "cat >> $APACHE_CONF" <<EOF

    DocumentRoot $WEBROOT
    DirectoryIndex index.html

    <Directory $WEBROOT>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    ErrorLog \${APACHE_LOG_DIR}/$DOMAIN-error.log
    CustomLog \${APACHE_LOG_DIR}/$DOMAIN-access.log combined
</VirtualHost>
EOF

    echo ">>> Enabling modules"
    sudo a2enmod rewrite ssl

    echo ">>> Enabling site"
    sudo a2ensite "$DOMAIN.conf"

    echo ">>> Reloading Apache"
    sudo systemctl reload apache2

    # Certbot --apache patches the config and creates the SSL vhost automatically
    echo ">>> Running Certbot"
    if [ -n "$WWW_DOMAIN" ]; then
        sudo certbot --apache -d "$DOMAIN" -d "$WWW_DOMAIN" --non-interactive --agree-tos -m admin@$DOMAIN
    else
        sudo certbot --apache -d "$DOMAIN" --non-interactive --agree-tos -m admin@$DOMAIN
    fi
fi

# Proxy mode: reload one final time to activate the rewritten SSL vhost
if [ -n "$PROXY_PORT" ]; then
    echo ">>> Final reload with SSL proxy vhost"
    sudo systemctl reload apache2
fi

echo ">>> Done!"
echo "Site available at: https://$DOMAIN"
