#!/bin/bash
# Info: SSL setup script for Polkadot Bootnode WSS
# Author: Provisioning System

set -e

DOMAIN="{{ polkadot_bootnode.wss.domain }}"
SSL_CERT_FILE="{{ polkadot_bootnode.wss.ssl.cert_file }}"
SSL_KEY_FILE="{{ polkadot_bootnode.wss.ssl.key_file }}"
EMAIL=${SSL_EMAIL:-admin@${DOMAIN}}

echo "Setting up SSL certificates for Polkadot Bootnode WSS..."

# Function to setup Let's Encrypt certificate
setup_letsencrypt() {
    echo "Setting up Let's Encrypt certificate for $DOMAIN..."
    
    # Stop nginx temporarily
    systemctl stop nginx 2>/dev/null || true
    
    # Generate certificate
    certbot certonly --standalone \
        --non-interactive \
        --agree-tos \
        --email "$EMAIL" \
        -d "$DOMAIN"
    
    # Copy certificates to expected locations
    cp "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" "$SSL_CERT_FILE"
    cp "/etc/letsencrypt/live/$DOMAIN/privkey.pem" "$SSL_KEY_FILE"
    
    # Set proper permissions
    chmod 644 "$SSL_CERT_FILE"
    chmod 600 "$SSL_KEY_FILE"
    chown root:root "$SSL_CERT_FILE" "$SSL_KEY_FILE"
    
    echo "Let's Encrypt certificate installed successfully"
}

# Function to generate self-signed certificate
setup_selfsigned() {
    echo "Generating self-signed certificate for $DOMAIN..."
    
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -keyout "$SSL_KEY_FILE" \
        -out "$SSL_CERT_FILE" \
        -subj "/C=US/ST=State/L=City/O=Organization/CN=$DOMAIN"
    
    # Set proper permissions
    chmod 644 "$SSL_CERT_FILE"
    chmod 600 "$SSL_KEY_FILE"
    chown root:root "$SSL_CERT_FILE" "$SSL_KEY_FILE"
    
    echo "Self-signed certificate generated successfully"
}

# Create certificate directories
mkdir -p "$(dirname "$SSL_CERT_FILE")"
mkdir -p "$(dirname "$SSL_KEY_FILE")"

# Setup certificate based on preference
case "${SSL_METHOD:-letsencrypt}" in
    "letsencrypt")
        setup_letsencrypt
        ;;
    "selfsigned")
        setup_selfsigned
        ;;
    *)
        echo "Invalid SSL method: ${SSL_METHOD}"
        echo "Use 'letsencrypt' or 'selfsigned'"
        exit 1
        ;;
esac

# Verify certificates
if [ -f "$SSL_CERT_FILE" ] && [ -f "$SSL_KEY_FILE" ]; then
    echo "SSL certificates installed:"
    echo "Certificate: $SSL_CERT_FILE"
    echo "Private key: $SSL_KEY_FILE"
    
    # Test certificate
    openssl x509 -in "$SSL_CERT_FILE" -noout -text | grep -E "(Subject:|Issuer:|Not After:)"
else
    echo "Error: SSL certificate setup failed"
    exit 1
fi

# Setup certificate renewal for Let's Encrypt
if [ "${SSL_METHOD:-letsencrypt}" = "letsencrypt" ]; then
    # Create renewal hook
    cat > /etc/letsencrypt/renewal-hooks/deploy/polkadot-bootnode.sh << 'EOF'
#!/bin/bash
# Copy renewed certificates
cp "/etc/letsencrypt/live/{{ polkadot_bootnode.wss.domain }}/fullchain.pem" "{{ polkadot_bootnode.wss.ssl.cert_file }}"
cp "/etc/letsencrypt/live/{{ polkadot_bootnode.wss.domain }}/privkey.pem" "{{ polkadot_bootnode.wss.ssl.key_file }}"

# Reload nginx
systemctl reload nginx

echo "Polkadot Bootnode SSL certificates renewed"
EOF
    
    chmod +x /etc/letsencrypt/renewal-hooks/deploy/polkadot-bootnode.sh
    echo "Certificate auto-renewal configured"
fi

echo "SSL setup completed successfully!"