#!/bin/bash

# InInventer Production Start Script
# This script obtains SSL certificates and starts all services

set -e

# Load environment variables
source .env.production

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

print_status() {
    echo -e "${GREEN}[STATUS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# Create required directories
print_status "Creating required directories..."
mkdir -p certbot/conf
mkdir -p certbot/www

# Start containers with initial configuration
print_status "Starting containers with initial configuration..."
cp nginx/initial.conf nginx/production.conf
docker-compose -f docker-compose.production.yml --env-file .env.production up -d nginx

# Wait for nginx to be ready
print_status "Waiting for Nginx to be ready..."
sleep 5

# Obtain SSL certificates
print_status "Obtaining SSL certificates for $DOMAIN_NAME..."
docker-compose -f docker-compose.production.yml --env-file .env.production run --rm certbot certonly \
    --webroot \
    --webroot-path=/var/www/certbot \
    --email $EMAIL_FOR_SSL \
    --agree-tos \
    --no-eff-email \
    -d $DOMAIN_NAME

# Check if certificates were obtained successfully
if [ ! -f "./certbot/conf/live/$DOMAIN_NAME/fullchain.pem" ]; then
    print_error "Failed to obtain SSL certificates!"
    exit 1
fi

print_status "SSL certificates obtained successfully!"

# Stop nginx
docker-compose -f docker-compose.production.yml --env-file .env.production down

# Create final Nginx configuration
print_status "Creating final Nginx configuration..."
cat > nginx/production.conf << EOL
server {
    listen 80;
    server_name $DOMAIN_NAME;
    
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    
    location / {
        return 301 https://\$server_name\$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name $DOMAIN_NAME;
    
    ssl_certificate /etc/letsencrypt/live/$DOMAIN_NAME/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN_NAME/privkey.pem;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    
    client_max_body_size 10M;
    
    # Security headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    
    location / {
        proxy_pass http://frontend:80;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_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;
    }
    
    location /api {
        proxy_pass http://backend:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_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

# Start all services
print_status "Starting all services..."
docker-compose -f docker-compose.production.yml --env-file .env.production up -d

# Wait for services to be ready
print_status "Waiting for services to be ready..."
sleep 10

# Check service status
print_status "Checking service status..."
docker-compose -f docker-compose.production.yml ps

# Create systemd service
print_status "Creating systemd service..."
cat > /etc/systemd/system/ininventer.service << EOL
[Unit]
Description=InInventer Application
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/opt/ininventer
ExecStart=/usr/local/bin/docker-compose -f docker-compose.production.yml --env-file .env.production up -d
ExecStop=/usr/local/bin/docker-compose -f docker-compose.production.yml down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOL

# Enable service
systemctl daemon-reload
systemctl enable ininventer.service

print_status "Deployment complete!"
print_status "Your application is now available at: https://$DOMAIN_NAME"
print_warning "Default login credentials:"
echo "  Email: admin@ininventer.com"
echo "  Password: admin123"
print_warning "IMPORTANT: Change the default password immediately after first login!"

# Show container logs
print_status "Recent logs:"
docker-compose -f docker-compose.production.yml logs --tail=20