#!/bin/bash

# Check arguments
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <domain> <VMID> <port>"
    exit 1
fi

DOMAIN=$1
VMID=$2
PORT=$3

# Path to Nginx configuration
NGINX_CONF="/etc/nginx/sites-available/$DOMAIN.conf"
NGINX_LINK="/etc/nginx/sites-enabled/$DOMAIN.conf"

# Get MAC address of the virtual machine
if [ -f "/etc/pve/local/qemu-server/$VMID.conf" ]; then
    MAC=$(grep "net0" "/etc/pve/local/qemu-server/$VMID.conf" | awk -F',' '{print $1}' | awk -F'=' '{print $2}')
elif [ -f "/etc/pve/local/lxc/$VMID.conf" ]; then
    MAC=$(grep "net0" "/etc/pve/local/lxc/$VMID.conf" | awk -F',' '{print $1}' | awk -F'=' '{print $2}')
else
    echo "VMID $VMID not found."
    exit 1
fi

# Get IP address from dnsmasq
IP=$(grep "$MAC" /var/lib/misc/dnsmasq.local.leases | awk '{print $3}')

if [ -z "$IP" ]; then
    echo "IP address for MAC $MAC not found."
    exit 1
fi

# Create Nginx configuration
cat <<EOL > "$NGINX_CONF"
server {
    listen 80;
    server_name $DOMAIN;

    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl;
    server_name $DOMAIN;

    ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        proxy_pass https://$IP:$PORT;
        proxy_set_header Host \$host;
		proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        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;
    }
}
EOL

# Create symbolic link in sites-enabled
ln -s "$NGINX_CONF" "$NGINX_LINK"

# Check Nginx configuration
nginx -t
if [ $? -ne 0 ]; then
    echo "Error in Nginx configuration."
    exit 1
fi

# Reload Nginx
systemctl reload nginx

# Run Certbot to get the certificate
certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos --email serty2005@gmail.com

# Renew certificates
certbot renew --dry-run

echo "Configuration for $DOMAIN created and certificate obtained successfully."
