#!/bin/bash

# Laravel Rsync Deployment Script for Beta Server
# Usage: ./rsync-deploy-beta.sh root@beta-server

# Check arguments
if [ $# -ne 1 ]; then
    echo "Usage: $0 <user@server>"
    echo "Example: $0 root@beta.example.com"
    echo ""
    echo "This will deploy to /var/www/hound on the beta server"
    exit 1
fi

SERVER="$1"
DEPLOY_PATH="/var/www/hound"

echo "🚀 Deploying Laravel app to $SERVER (BETA)"
echo "   📁 Deploy path → $DEPLOY_PATH"

# Build application locally
echo "📦 Building Laravel application for production..."

# Exit on any error
set -e

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

# Install PHP dependencies (production only)
echo "🔧 Installing PHP dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

# Clear existing caches (skip during build to preserve manifest)
echo "🧹 Clearing caches..."
php artisan config:clear
php artisan route:clear
php artisan view:clear

# Cache everything for production
echo "⚡ Caching for production..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

# Create beta .env file (you'll need to customize this with beta credentials)
echo "⚙️  Creating beta .env file..."
cat > .env.beta << 'EOF'
APP_NAME="Musical Marketplace (Beta)"
APP_ENV=staging
APP_KEY=base64:FiC0KpZywsGxm+gtszP8hCAohaZIoLS+zRV8ipM4kLU=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=https://hound.xeek.com

APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US

APP_MAINTENANCE_DRIVER=file
APP_MAINTENANCE_STORE=database

BCRYPT_ROUNDS=12

LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=beta_market
DB_USERNAME=beta_user
DB_PASSWORD=CHANGEME

SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null

BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database

CACHE_STORE=database
CACHE_PREFIX=

MEMCACHED_HOST=127.0.0.1

REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=resend
RESEND_KEY=re_gjpdksUt_7rxt1oNWkU8CDpuYNq2S4yJj
MAIL_FROM_ADDRESS="noreply@xeek.com"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

VITE_APP_NAME="${APP_NAME}"
EOF

# Set proper permissions
echo "🔐 Setting permissions..."
chmod -R 755 storage bootstrap/cache
chmod -R 775 storage/logs storage/framework

echo "✅ Build complete!"

echo "📤 Testing connection to server..."

# Test SSH connection first
echo "🔍 Testing SSH connection..."
if ! ssh -o ConnectTimeout=10 -o BatchMode=yes "$SERVER" 'echo "SSH connection successful"'; then
    echo "❌ SSH connection failed! Please check:"
    echo "   - Server address: $SERVER"
    echo "   - SSH key authentication"
    echo "   - Network connectivity"
    exit 1
fi

echo "✅ SSH connection successful"

# Create directory if it doesn't exist
echo "🔍 Ensuring remote directory exists..."
ssh "$SERVER" "mkdir -p $DEPLOY_PATH"

echo "📤 Syncing files to beta server..."

# Sync all files to beta
rsync -az --delete --force \
    --exclude='.git' \
    --exclude='.env' \
    --exclude='node_modules' \
    --exclude='tests' \
    --exclude='.gitignore' \
    --exclude='.gitattributes' \
    --exclude='README.md' \
    --exclude='*.md' \
    --exclude='.phpunit.result.cache' \
    --exclude='phpunit.xml' \
    --exclude='vite.config.js' \
    --exclude='package.json' \
    --exclude='package-lock.json' \
    --exclude='composer.lock' \
    --exclude='.editorconfig' \
    --exclude='*.sql' \
    --exclude='sql/' \
    --exclude='backup*.sql' \
    ./ "$SERVER:$DEPLOY_PATH/" 2>/dev/null

# Check rsync exit code
RSYNC_EXIT_CODE=$?
if [ $RSYNC_EXIT_CODE -eq 0 ]; then
    echo "✅ Files synced successfully!"
else
    echo "❌ Rsync failed with exit code: $RSYNC_EXIT_CODE"
    exit 1
fi

echo ""
echo "🎉 Deployment complete!"
echo ""
echo "🔧 Finalizing deployment on server..."
ssh "$SERVER" << 'ENDSSH'
cd /var/www/hound

# Backup existing .env if it exists
if [ -f .env ]; then
    cp .env .env.backup.$(date +%Y%m%d_%H%M%S)
fi

# Only copy .env.beta to .env if .env doesn't exist (preserve existing config)
if [ ! -f .env ]; then
    mv .env.beta .env
    echo "⚠️  New .env created from .env.beta - PLEASE UPDATE DATABASE CREDENTIALS!"
else
    echo "ℹ️  Existing .env preserved. New config in .env.beta for reference."
fi

php artisan config:clear
php artisan view:clear
php artisan cache:clear
rm -rf storage/framework/views/*
rm -rf storage/framework/cache/data/*
php artisan config:cache
php artisan migrate --force
php artisan storage:link
php artisan queue:restart
chmod -R 775 storage bootstrap/cache
ENDSSH

if [ $? -eq 0 ]; then
    echo "✅ Server setup completed successfully!"
else
    echo "❌ Server setup failed. Manual steps may be needed:"
    echo "1. cd /var/www/hound"
    echo "2. Check .env configuration"
    echo "3. php artisan config:clear"
    echo "4. php artisan config:cache"
    echo "5. php artisan migrate --force"
    echo "6. php artisan storage:link"
    echo "7. chmod -R 775 storage bootstrap/cache"
fi
echo ""
echo "⚠️  IMPORTANT: Verify .env settings on beta server match your beta database!"
echo ""
