#!/bin/bash
# deploy.dev.sh — Deploy to dev server (20.236.64.82)
# Usage: ./deploy.dev.sh [branch]
# Default branch: upgrade-symfony8

set -euo pipefail

BRANCH=${1:-upgrade-symfony8}
PROJECT_DIR="/var/www/html/academia_test"

echo "====================================="
echo "  Deploying branch: $BRANCH"
echo "  To: $PROJECT_DIR"
echo "====================================="

cd "$PROJECT_DIR"

# Discard any local changes on the server
sudo git checkout .

# Switch to the branch (create tracking branch if needed)
sudo git switch "$BRANCH" 2>/dev/null || sudo git switch -c "$BRANCH" "origin/$BRANCH"

# Pull latest
sudo git pull origin "$BRANCH"

# Copy the dev environment file
if [ -f .env.dev ]; then
    echo ">>> Copying .env.dev → .env.local"
    sudo cp .env.dev .env.local
fi

# Install dependencies (no dev packages in deployed env)
sudo composer install --no-dev --optimize-autoloader --no-interaction

# Clear and warm up cache
sudo -u www-data php bin/console cache:warmup --env=prod

# Fix permissions
sudo chown -R www-data:www-data var/cache/
sudo chown -R www-data:www-data var/log/
sudo chown -R www-data:www-data public/uploads/ 2>/dev/null || true

# Run database migrations (safe for Symfony 8)
sudo php bin/console doctrine:migrations:migrate --no-interaction --allow-no-migration 2>/dev/null || {
    echo ">>> Migrations failed, falling back to schema:update"
    sudo php bin/console doctrine:schema:update --force
}

# Setup messenger transport table
sudo php bin/console messenger:setup-transports 2>/dev/null || {
    echo ">>> messenger:setup-transports failed (MariaDB issue?), check deploy_notes.md for manual SQL"
}

# Install assets
sudo php bin/console assets:install --symlink

# Create required upload directories
sudo mkdir -p public/uploads/privateCard/partnerContent
sudo mkdir -p public/uploads/references
sudo chown -R www-data:www-data public/uploads/

# Restart messenger worker if running
sudo systemctl restart shamra-messenger-worker 2>/dev/null || {
    echo ">>> Messenger worker service not set up yet — see deploy_notes.md"
}

# Restart Apache to pick up any PHP changes
sudo systemctl restart apache2

echo "====================================="
echo "  Deploy complete!"
echo "  Site: http://20.236.64.82"
echo "====================================="
