#!/bin/bash

# Beta Deployment Script using Git Pull
# Usage: ./deploy-beta.sh [branch-name]
# If no branch specified, uses current branch

SERVER="root@hound.xeek.com"
DEPLOY_PATH="/var/www/hound"

# Get current branch if not specified
if [ $# -eq 0 ]; then
    BRANCH=$(git branch --show-current)
    echo "No branch specified, using current branch: $BRANCH"
else
    BRANCH="$1"
fi

echo "🚀 Deploying branch '$BRANCH' to beta server"
echo ""

# Check if there are uncommitted changes
if ! git diff-index --quiet HEAD --; then
    echo "⚠️  Warning: You have uncommitted changes"
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Push current branch to GitHub
echo "📤 Pushing to GitHub..."
git push origin "$BRANCH"

if [ $? -ne 0 ]; then
    echo "❌ Git push failed!"
    exit 1
fi

echo "✅ Pushed to GitHub"
echo ""

# Deploy on beta server
echo "🔧 Deploying on beta server..."
ssh "$SERVER" << ENDSSH
set -e

cd $DEPLOY_PATH

echo "📥 Pulling latest code from GitHub..."
git fetch origin
git checkout $BRANCH
git pull origin $BRANCH

echo "🔧 Installing dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

echo "📦 Building frontend assets..."
npm ci --production=false
npm run build

echo "🧹 Clearing caches..."
php artisan config:clear
php artisan view:clear
php artisan cache:clear
php artisan route:clear

echo "⚡ Caching for production..."
php artisan config:cache
php artisan view:cache
php artisan route:cache

echo "🗄️  Running migrations..."
php artisan migrate --force

echo "🔗 Ensuring storage link exists..."
php artisan storage:link

echo "🔄 Restarting queue workers..."
php artisan queue:restart

echo "🔐 Setting permissions..."
chmod -R 775 storage bootstrap/cache

echo "✅ Deployment complete!"
ENDSSH

if [ $? -eq 0 ]; then
    echo ""
    echo "🎉 Beta deployment successful!"
    echo "🌐 Site: https://hound.xeek.com"
else
    echo ""
    echo "❌ Deployment failed on server"
    exit 1
fi
