#!/usr/bin/env bash

# ==============================================================================
# MT5 Trade Copier SaaS Dashboard — Server Deployment Script
# Debian 13 / Linux Server Auto Deployment
# ==============================================================================

set -e

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$APP_DIR"

echo "========================================="
echo "🚀 Starting Deployment for Copier Dashboard"
echo "📂 Path: $APP_DIR"
echo "⏰ Time: $(date)"
echo "========================================="

# 1. Pull latest commits
echo "📥 1/5 Pulling latest changes from Git..."
git fetch --all
git reset --hard origin/$(git rev-parse --abbrev-ref HEAD)

# 2. Composer Dependencies
echo "📦 2/5 Installing Composer dependencies (no-dev)..."
composer install --no-dev --prefer-dist --no-interaction --optimize-autoloader

# 3. Database Migrations
echo "🗄️ 3/5 Running database migrations..."
php spark migrate --all

# 4. Clear & Warmup Caches
echo "🧹 4/5 Clearing system caches..."
php spark cache:clear || true

# 5. Ensure writable folders exist & fix permissions for Apache / PHP-FPM
echo "🔒 5/5 Ensuring writable/ structure and setting permissions..."
mkdir -p "$APP_DIR/writable/cache" "$APP_DIR/writable/logs" "$APP_DIR/writable/session" "$APP_DIR/writable/uploads" "$APP_DIR/writable/debugbar"
if id -u www-data >/dev/null 2>&1; then
    chown -R www-data:www-data "$APP_DIR/writable"
fi
chmod -R 775 "$APP_DIR/writable"

echo "========================================="
echo "✅ Deployment Finished Successfully!"
echo "========================================="
