#!/bin/bash

# ==============================================================================
# SEGYRIC VPN / LARAVEL BACKEND AUTOMATED DEPLOYMENT SCRIPT
# ==============================================================================
# Usage: ./deploy.sh
# ==============================================================================

set -e

echo -e "\e[34m==================================================\e[0m"
echo -e "\e[36m🚀 Starting Segyric VPN Server Automated Deployment...\e[0m"
echo -e "\e[34m==================================================\e[0m"

# 1. Pull latest code if Git is initialized
if [ -d ".git" ]; then
    echo -e "\e[33m[1/7] Pulling latest updates from Git...\e[0m"
    git pull origin main || echo "Git pull skipped or clean."
else
    echo -e "\e[33m[1/7] Git directory not found. Skipping git pull...\e[0m"
fi

# 2. Check for .env file
if [ ! -f ".env" ]; then
    echo -e "\e[33m[2/7] .env file not found! Copying from .env.example...\e[0m"
    cp .env.example .env
    php artisan key:generate
    echo -e "\e[31m[!] Please edit your .env file with production database and URL settings before re-running.\e[0m"
else
    echo -e "\e[32m[2/7] Production .env file verified.\e[0m"
fi

# 3. Install Composer Dependencies (Production Mode)
echo -e "\e[33m[3/7] Installing Composer production dependencies...\e[0m"
composer install --no-dev --optimize-autoloader

# 4. Run Database Migrations & Seeders
echo -e "\e[33m[4/7] Running database migrations & seeding 25+ real VPN servers...\e[0m"
php artisan migrate --force
php artisan db:seed --class=VpnServerSeeder --force

# 5. Optimize Caches
echo -e "\e[33m[5/7] Clearing & caching configuration, routes, and views...\e[0m"
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 6. Set Directory Permissions
echo -e "\e[33m[6/7] Setting file storage permissions...\e[0m"
chmod -R 775 storage bootstrap/cache
if id "www-data" &>/dev/null; then
    chown -R www-data:www-data storage bootstrap/cache
fi

# 7. Reload Web Server if systemctl exists
echo -e "\e[33m[7/7] Reloading web services...\e[0m"
if command -v systemctl &> /dev/null; then
    sudo systemctl reload nginx 2>/dev/null || true
    sudo systemctl restart php8.2-fpm 2>/dev/null || true
fi

echo -e "\e[34m==================================================\e[0m"
echo -e "\e[32m✅ Segyric VPN Server Deployment Completed Successfully!\e[0m"
echo -e "\e[34m==================================================\e[0m"
