#!/bin/bash
# RealCV Deployment Script
# Run this from your development machine to deploy to a Linux server

set -e

# Configuration - UPDATE THESE VALUES
SERVER_USER="deploy"
SERVER_HOST="your-server.com"
SERVER_PATH="/var/www/realcv"
DOMAIN="realcv.yourdomain.com"

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

echo -e "${GREEN}=== RealCV Deployment Script ===${NC}"

# Check if configuration is set
if [[ "$SERVER_HOST" == "your-server.com" ]]; then
    echo -e "${RED}Error: Please update SERVER_HOST in this script${NC}"
    exit 1
fi

# Step 1: Build and publish
echo -e "${YELLOW}Step 1: Publishing application...${NC}"
cd "$(dirname "$0")/.."
dotnet publish src/RealCV.Web -c Release -o ./publish --nologo

# Step 2: Create deployment package
echo -e "${YELLOW}Step 2: Creating deployment package...${NC}"
tar -czf deploy/realcv-release.tar.gz -C publish .

# Step 3: Transfer to server
echo -e "${YELLOW}Step 3: Transferring to server...${NC}"
scp deploy/realcv-release.tar.gz ${SERVER_USER}@${SERVER_HOST}:/tmp/

# Step 4: Deploy on server
echo -e "${YELLOW}Step 4: Deploying on server...${NC}"
ssh ${SERVER_USER}@${SERVER_HOST} << 'ENDSSH'
set -e

# Stop the service if running
sudo systemctl stop realcv 2>/dev/null || true

# Backup current deployment
if [ -d "/var/www/realcv" ]; then
    sudo mv /var/www/realcv /var/www/realcv.backup.$(date +%Y%m%d_%H%M%S)
fi

# Create directory and extract
sudo mkdir -p /var/www/realcv
sudo tar -xzf /tmp/realcv-release.tar.gz -C /var/www/realcv
sudo chown -R www-data:www-data /var/www/realcv

# Start the service
sudo systemctl start realcv

# Clean up
rm /tmp/realcv-release.tar.gz

echo "Deployment complete on server"
ENDSSH

# Step 5: Verify deployment
echo -e "${YELLOW}Step 5: Verifying deployment...${NC}"
sleep 3
if ssh ${SERVER_USER}@${SERVER_HOST} "sudo systemctl is-active realcv" | grep -q "active"; then
    echo -e "${GREEN}=== Deployment successful! ===${NC}"
    echo -e "Site should be available at: https://${DOMAIN}"
else
    echo -e "${RED}Warning: Service may not be running. Check with: sudo systemctl status realcv${NC}"
fi

# Cleanup local files
rm -f deploy/realcv-release.tar.gz

echo -e "${GREEN}Done!${NC}"
