#!/bin/bash

# Deployment Script for MindPad frontend (Vite SPA) to server
# Usage:
#   ./deploy-to-server.sh user@host /remote/path
#   ./deploy-to-server.sh user host /remote/path

set -e

echo "🚀 Starting deployment process..."

# Build the project
echo "📦 Building project..."
npm run build

if [ ! -d "dist" ]; then
    echo "❌ Error: dist folder not found. Build failed?"
    exit 1
fi

echo "✅ Build completed successfully"

# Parse args: support "user@host /path" (2 args) or "user host /path" (3 args)
if [ -z "$1" ] || [ -z "$2" ]; then
    echo ""
    echo "📁 Build files are ready in the 'dist' folder"
    echo ""
    echo "To deploy manually:"
    echo "1. Upload the contents of the 'dist' folder to your web server"
    echo "2. App uses HashRouter (#/login); server only needs to serve index.html for /"
    echo "3. Set permissions: 755 for directories, 644 for files"
    echo ""
    echo "Or use this script with server details:"
    echo "  ./deploy-to-server.sh user@host /var/www/notepad"
    echo "  ./deploy-to-server.sh user hostname /var/www/notepad"
    echo ""
    exit 0
fi

if [ -z "$3" ]; then
    SERVER_SSH="$1"
    SERVER_PATH="$2"
else
    SERVER_SSH="$1@$2"
    SERVER_PATH="$3"
fi

echo "📤 Uploading files to server..."
echo "   Server: $SERVER_SSH"
echo "   Path: $SERVER_PATH"

# Upload files using rsync
if command -v rsync &> /dev/null; then
    echo "Using rsync..."
    rsync -avz --delete \
        dist/ \
        "$SERVER_SSH:$SERVER_PATH/"

    echo ""
    echo "🔧 Setting file permissions on server..."
    ssh "$SERVER_SSH" "chmod -R 755 \"$SERVER_PATH\" && find \"$SERVER_PATH\" -type f -exec chmod 644 {} \;"

    echo ""
    echo "✅ Deployment completed successfully!"
    echo "🌐 App URL: https://notepad.prasowlabs.in (or your configured domain)"
else
    echo "❌ rsync not found. Install rsync or upload the dist/ folder manually."
    exit 1
fi
