#!/bin/bash

# Configuration
SERVER_USER="root"
SERVER_HOST="107.189.27.14"
PROJECT_PATH="/var/www/nest-khianat"
PM2_PROCESS="khianat-2002"
NVM_PATH="/root/.nvm/nvm.sh"

# Function to show help
show_help() {
    cat <<EOF
Usage: $0 [COMMAND]

COMMANDS:
    start       Start the PM2 process
    stop        Stop the PM2 process  
    restart     Restart the PM2 process
    status      Show process status
    logs        Show process logs
    delete      Delete the PM2 process
    
Examples:
    $0 start
    $0 logs
    $0 restart
EOF
}

# Function to execute PM2 command
pm2_command() {
    local command="$1"
    local remote_commands=$(cat <<EOF
source ${NVM_PATH}
cd ${PROJECT_PATH}
pm2 ${command} ${PM2_PROCESS}
EOF
)
    
    echo "🔧 Executing: pm2 ${command} ${PM2_PROCESS}"
    ssh ${SERVER_USER}@${SERVER_HOST} "${remote_commands}"
}

# Main execution
main() {
    case "$1" in
        start|stop|restart|delete)
            pm2_command "$1"
            ;;
        status)
            pm2_command "show"
            ;;
        logs)
            pm2_command "logs --lines 50"
            ;;
        -h|--help|"")
            show_help
            ;;
        *)
            echo "❌ Unknown command: $1"
            show_help
            exit 1
            ;;
    esac
}

main "$@"