#!/bin/bash

# Laravel Rsync Deployment Script with separated public/private files
# Usage: ./rsync-deploy.sh user@server.com

# Check arguments
if [ $# -ne 1 ]; then
    echo "Usage: $0 <user@server>"
    echo "Example: $0 user@myserver.com"
    echo ""
    echo "This will deploy:"
    echo "  - Public files → ~/public_html/"
    echo "  - Private files → ~/private/"
    exit 1
fi

SERVER="$1"
PRIVATE_PATH="~/private"
PUBLIC_PATH="~/public_html"

echo "🚀 Deploying Laravel app to $SERVER"
echo "   📁 Private files → $PRIVATE_PATH"
echo "   🌐 Public files → $PUBLIC_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 production .env file
echo "⚙️  Creating production .env file..."
cat > .env.production << 'EOF'
APP_NAME="Musical Marketplace"
APP_ENV=production
APP_KEY=base64:FiC0KpZywsGxm+gtszP8hCAohaZIoLS+zRV8ipM4kLU=
APP_DEBUG=false
APP_TIMEZONE=UTC
APP_URL=https://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=error

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=metajack_market
DB_USERNAME=mjack
DB_PASSWORD=NnBSN9i2xUKg

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=log
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.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 directories if they don't exist
echo "🔍 Ensuring remote directories exist..."
ssh "$SERVER" "mkdir -p $PRIVATE_PATH $PUBLIC_PATH"

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

# Sync private files (everything except public directory)
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='public' \
    ./ "$SERVER:$PRIVATE_PATH/" 2>/dev/null

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

echo "🌐 Syncing public files to server..."

# Sync public files only
rsync -az --delete \
    ./public/ "$SERVER:$PUBLIC_PATH/"

# Check public files rsync exit code
PUBLIC_EXIT_CODE=$?
if [ $PUBLIC_EXIT_CODE -eq 0 ]; then
    echo "✅ Public files synced successfully!"
else
    echo "❌ Public files rsync failed with exit code: $PUBLIC_EXIT_CODE"
    exit 1
fi
echo ""
echo "🎉 Deployment complete!"
echo ""
echo "📁 File structure on server:"
echo "   ~/private/          - Laravel application files"
echo "   ~/public_html/      - Web-accessible files"
echo ""
echo "🔧 Finalizing deployment on server..."
ssh "$SERVER" << 'ENDSSH'
cd ~/private
mv .env.production .env
/usr/local/bin/php8.2 artisan config:clear
/usr/local/bin/php8.2 artisan view:clear
/usr/local/bin/php8.2 artisan cache:clear
rm -rf storage/framework/views/*
rm -rf storage/framework/cache/data/*
/usr/local/bin/php8.2 artisan config:cache
/usr/local/bin/php8.2 artisan migrate --force
/usr/local/bin/php8.2 artisan db:seed --class=DefaultUsersSeeder
/usr/local/bin/php8.2 artisan queue:restart
rm -f ~/public_html/storage
ln -sf ~/private/storage/app/public ~/public_html/storage
# Sync manifest file so Laravel uses correct asset hashes
cp ~/public_html/build/manifest.json ~/private/public/build/manifest.json
chmod -R 775 storage bootstrap/cache
ENDSSH

if [ $? -eq 0 ]; then
    echo "✅ Server setup completed successfully!"
else
    echo "❌ Server setup failed. Manual steps needed:"
    echo "1. cd ~/private"
    echo "2. mv .env.production .env"
    echo "3. /usr/local/bin/php8.2 artisan config:clear"
    echo "4. /usr/local/bin/php8.2 artisan config:cache"
    echo "5. /usr/local/bin/php8.2 artisan migrate --force"
    echo "6. rm -f ~/public_html/storage && ln -sf ~/private/storage/app/public ~/public_html/storage"
    echo "7. chmod -R 775 storage bootstrap/cache"
fi
echo ""
echo "🌐 Web server setup:"
echo "   - Document root should point to: ~/public_html/"
echo "   - Update ~/public_html/index.php to point to ~/private/"
echo ""
