#!/bin/bash
# install-nginx.sh - Install nginx configuration and SSL for api.press.zone
# Run this as root on the server

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}ERROR:${NC} This script must be run as root"
    exit 1
fi

echo -e "${GREEN}Installing nginx configuration for api.press.zone...${NC}"

# Install certbot if not installed
if ! command -v certbot &> /dev/null; then
    echo "Installing certbot..."
    dnf install -y certbot python3-certbot-nginx || yum install -y certbot python3-certbot-nginx
fi

# Create certbot webroot
mkdir -p /var/www/certbot

# Copy nginx configuration
echo "Copying nginx configuration..."
cp nginx/api.press.zone.conf /etc/nginx/conf.d/

# Test nginx configuration
echo "Testing nginx configuration..."
nginx -t || {
    echo -e "${RED}ERROR:${NC} Nginx configuration test failed"
    exit 1
}

# Reload nginx
echo "Reloading nginx..."
systemctl reload nginx

# Obtain SSL certificate
echo -e "${YELLOW}Obtaining SSL certificate from Let's Encrypt...${NC}"
certbot certonly --webroot \
    -w /var/www/certbot \
    -d api.press.zone \
    --non-interactive \
    --agree-tos \
    --email admin@press.zone \
    --keep-until-expiring || {
    echo -e "${RED}ERROR:${NC} Failed to obtain SSL certificate"
    echo "Please check that:"
    echo "  1. DNS is properly configured for api.press.zone"
    echo "  2. Port 80 is accessible from the internet"
    echo "  3. Firewall allows HTTP/HTTPS traffic"
    exit 1
}

# Update nginx config to use SSL
echo "Updating nginx configuration with SSL..."
cp nginx/api.press.zone.conf /etc/nginx/conf.d/

# Test nginx configuration again
echo "Testing nginx configuration with SSL..."
nginx -t || {
    echo -e "${RED}ERROR:${NC} Nginx configuration test failed with SSL"
    exit 1
}

# Reload nginx
echo "Reloading nginx with SSL..."
systemctl reload nginx

# Setup auto-renewal
echo "Setting up SSL certificate auto-renewal..."
systemctl enable certbot-renew.timer
systemctl start certbot-renew.timer

# Add renewal hook to reload nginx
mkdir -p /etc/letsencrypt/renewal-hooks/deploy/
cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'EOF'
#!/bin/bash
systemctl reload nginx
EOF
chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh

echo -e "${GREEN}✓ Nginx and SSL installed successfully!${NC}"
echo ""
echo "Configuration details:"
echo "  Domain: api.press.zone"
echo "  SSL Certificate: /etc/letsencrypt/live/api.press.zone/"
echo "  Nginx Config: /etc/nginx/conf.d/api.press.zone.conf"
echo "  Logs: /var/log/nginx/api.press.zone.*.log"
echo ""
echo "Test the setup:"
echo "  curl https://api.press.zone/health"
