#!/bin/bash
# RealCV Server Setup Script
# Run this ONCE on a fresh Linux server (Ubuntu 22.04/24.04)

set -e

# Configuration - UPDATE THESE VALUES
DOMAIN="realcv.yourdomain.com"
DB_PASSWORD="YourStrong!Password123"
ADMIN_EMAIL="admin@yourdomain.com"

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

echo -e "${GREEN}=== RealCV Server Setup ===${NC}"

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

# Step 1: Update system
echo -e "${YELLOW}Step 1: Updating system...${NC}"
apt update && apt upgrade -y

# Step 2: Install .NET 8 Runtime
echo -e "${YELLOW}Step 2: Installing .NET 8 Runtime...${NC}"
apt install -y wget apt-transport-https
wget https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
dpkg -i packages-microsoft-prod.deb
rm packages-microsoft-prod.deb
apt update
apt install -y aspnetcore-runtime-8.0

# Step 3: Install Nginx
echo -e "${YELLOW}Step 3: Installing Nginx...${NC}"
apt install -y nginx
systemctl enable nginx

# Step 4: Install Docker (for SQL Server)
echo -e "${YELLOW}Step 4: Installing Docker...${NC}"
apt install -y docker.io docker-compose
systemctl enable docker
systemctl start docker

# Step 5: Set up SQL Server container
echo -e "${YELLOW}Step 5: Setting up SQL Server...${NC}"
docker run -e 'ACCEPT_EULA=Y' \
    -e "SA_PASSWORD=${DB_PASSWORD}" \
    -p 127.0.0.1:1433:1433 \
    --name realcv-sql \
    --restart unless-stopped \
    -v realcv-sqldata:/var/opt/mssql \
    -d mcr.microsoft.com/mssql/server:2022-latest

echo "Waiting for SQL Server to start..."
sleep 30

# Create the database
docker exec realcv-sql /opt/mssql-tools18/bin/sqlcmd \
    -S localhost -U SA -P "${DB_PASSWORD}" -C \
    -Q "CREATE DATABASE RealCV"

# Step 6: Create application directory
echo -e "${YELLOW}Step 6: Creating application directory...${NC}"
mkdir -p /var/www/realcv
chown -R www-data:www-data /var/www/realcv

# Step 7: Create systemd service
echo -e "${YELLOW}Step 7: Creating systemd service...${NC}"
cat > /etc/systemd/system/realcv.service << EOF
[Unit]
Description=RealCV Web Application
After=network.target docker.service
Requires=docker.service

[Service]
WorkingDirectory=/var/www/realcv
ExecStart=/usr/bin/dotnet /var/www/realcv/RealCV.Web.dll
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=realcv
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://localhost:5000
Environment=ConnectionStrings__DefaultConnection=Server=127.0.0.1;Database=RealCV;User Id=SA;Password=${DB_PASSWORD};TrustServerCertificate=True

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable realcv

# Step 8: Configure Nginx
echo -e "${YELLOW}Step 8: Configuring Nginx...${NC}"
cat > /etc/nginx/sites-available/realcv << EOF
server {
    listen 80;
    server_name ${DOMAIN};

    location / {
        proxy_pass http://localhost:5000;
        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;
        proxy_cache_bypass \$http_upgrade;

        # WebSocket support for Blazor Server
        proxy_read_timeout 86400;
        proxy_send_timeout 86400;
    }
}
EOF

ln -sf /etc/nginx/sites-available/realcv /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl reload nginx

# Step 9: Install Certbot for SSL
echo -e "${YELLOW}Step 9: Setting up SSL with Let's Encrypt...${NC}"
apt install -y certbot python3-certbot-nginx

echo -e "${YELLOW}To enable SSL, run:${NC}"
echo "  certbot --nginx -d ${DOMAIN} --email ${ADMIN_EMAIL} --agree-tos --non-interactive"

# Step 10: Configure firewall
echo -e "${YELLOW}Step 10: Configuring firewall...${NC}"
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

# Summary
echo ""
echo -e "${GREEN}=== Server Setup Complete! ===${NC}"
echo ""
echo "Next steps:"
echo "1. Update DNS to point ${DOMAIN} to this server's IP"
echo "2. Deploy the application using deploy.sh from your dev machine"
echo "3. Run SSL setup: certbot --nginx -d ${DOMAIN}"
echo ""
echo "Useful commands:"
echo "  sudo systemctl status realcv     - Check app status"
echo "  sudo journalctl -u realcv -f     - View app logs"
echo "  docker logs realcv-sql           - View SQL Server logs"
echo ""
echo -e "${YELLOW}Database connection string:${NC}"
echo "  Server=127.0.0.1;Database=RealCV;User Id=SA;Password=${DB_PASSWORD};TrustServerCertificate=True"
