#!/bin/bash

# Update package list and install required packages
echo "Updating package list..."
sudo apt update -y

# Install Nginx
echo "Installing Nginx..."
sudo apt install -y nginx

# Install OpenSSL to generate self-signed certificates
echo "Installing OpenSSL..."
sudo apt install -y openssl

# Create directory to store SSL certificates
echo "Creating SSL directories..."
sudo mkdir -p /etc/ssl/certs
sudo mkdir -p /etc/ssl/private

# Generate the private key and self-signed certificate
echo "Generating self-signed certificate..."
sudo openssl req -x509 -newkey rsa:4096 -keyout /etc/ssl/private/selfsigned.key -out /etc/ssl/certs/selfsigned.crt -days 365 -nodes

# Create Nginx configuration for Gitea with SSL
echo "Creating Nginx configuration for Gitea with SSL..."
cat <<EOF | sudo tee /etc/nginx/sites-available/gitea
server {
    listen 80;
    server_name ec2-13-201-225-130.ap-south-1.compute.amazonaws.com;

    # Redirect HTTP to HTTPS
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl;
    server_name ec2-13-201-225-130.ap-south-1.compute.amazonaws.com;

    # Self-signed certificate
    ssl_certificate /etc/ssl/certs/selfsigned.crt;
    ssl_certificate_key /etc/ssl/private/selfsigned.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5';
    ssl_prefer_server_ciphers on;

    location /git/ {
        proxy_pass http://127.0.0.1:3000/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_redirect off;
    }
}
EOF

# Enable the Nginx configuration
echo "Enabling Nginx configuration..."
sudo ln -s /etc/nginx/sites-available/gitea /etc/nginx/sites-enabled/

# Test Nginx configuration
echo "Testing Nginx configuration..."
sudo nginx -t

# Restart Nginx to apply changes
echo "Restarting Nginx..."
sudo systemctl restart nginx

# Final message
echo "Nginx with self-signed SSL is installed and configured. Your site should now be accessible over HTTPS at https://ec2-13-201-225-130.ap-south-1.compute.amazonaws.com/git"