#!/bin/bash
set -e

# Ensure running with sudo/root
if [ "$EUID" -ne 0 ]; then
  echo "Error: Please run with sudo (e.g., sudo ./createfolder.sh <folder_name> <domain>)"
  exit 1
fi

FOLDER="$1"
DOMAIN="$2"

# Prompt for values if not passed as arguments
if [ -z "$FOLDER" ]; then
  read -p "Enter folder name (e.g., theme): " FOLDER
fi

if [ -z "$DOMAIN" ]; then
  read -p "Enter full domain (e.g., theme.aakuna.net.au): " DOMAIN
fi

DOC_ROOT="/var/www/$FOLDER/public_html"
VHOST_FILE="/etc/apache2/sites-available/$DOMAIN.conf"

echo ""
echo "==> Creating /var/www/$FOLDER/public_html..."
mkdir -p "$DOC_ROOT"

# Sample placeholder page
cat <<EOF > "$DOC_ROOT/index.html"
<!DOCTYPE html>
<html>
<head><title>$DOMAIN</title></head>
<body style="font-family:sans-serif; text-align:center; padding-top:50px;">
    <h1>$DOMAIN is active!</h1>
    <p>Serving from /var/www/$FOLDER/public_html</p>
</body>
</html>
EOF

chown -R www-data:www-data "/var/www/$FOLDER"
chmod -R 755 "/var/www/$FOLDER"

echo "==> Creating Apache VHost: $VHOST_FILE..."
cat <<EOF > "$VHOST_FILE"
<VirtualHost *:80>
    ServerName $DOMAIN
    DocumentRoot $DOC_ROOT

    <Directory $DOC_ROOT>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Preserve Cloudflare / AWS reverse proxy HTTPS status
    SetEnvIf X-Forwarded-Proto "^https$" HTTPS=on

    ErrorLog \${APACHE_LOG_DIR}/${DOMAIN}_error.log
    CustomLog \${APACHE_LOG_DIR}/${DOMAIN}_access.log combined
</VirtualHost>
EOF

echo "==> Enabling site and reloading Apache..."
a2ensite "$DOMAIN.conf" > /dev/null
apache2ctl configtest
systemctl reload apache2

echo ""
echo "Site is now live locally and on port 80!"
echo "Make sure you added the DNS 'A' record in Cloudflare pointing '$DOMAIN' to 3.24.107.252."
echo ""

# Wait for confirmation before executing Certbot
read -p "Run Certbot for $DOMAIN now? (y/n): " RUN_CERTBOT

if [[ "$RUN_CERTBOT" =~ ^[Yy]$ ]]; then
    echo "==> Requesting certificate from Let's Encrypt..."
    certbot --apache -d "$DOMAIN" --non-interactive --agree-tos --register-unsafely-without-email --redirect || {
        echo "Certbot encounter an issue. Run manually: sudo certbot --apache -d $DOMAIN"
        exit 1
    }
    echo "==> Certbot finished! HTTPS is active."
else
    echo "Skipped Certbot. You can run it whenever you are ready:"
    echo "sudo certbot --apache -d $DOMAIN"
fi

echo ""
echo "Done! Path: $DOC_ROOT"
