#!/bin/bash

# Create nginx config for dashboard.tools.hihala.com
sudo tee /etc/nginx/sites-available/dashboard.tools.hihala.com > /dev/null <<'EOF'
server {
    listen 80;
    listen [::]:80;
    server_name dashboard.tools.hihala.com;

    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }

    location / {
        proxy_pass http://127.0.0.1:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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;
    }
}
EOF

sudo ln -sf /etc/nginx/sites-available/dashboard.tools.hihala.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

# Test ACME challenge path
sudo mkdir -p /var/www/html/.well-known/acme-challenge/
echo "test" | sudo tee /var/www/html/.well-known/acme-challenge/test
curl -s http://dashboard.tools.hihala.com/.well-known/acme-challenge/test && echo " - OK"
rm -f /var/www/html/.well-known/acme-challenge/test

# Run certbot
sudo certbot --nginx -d dashboard.tools.hihala.com
