#!/bin/bash

# Script: stopvnc
# Purpose: Stop TigerVNC server running on specified port
# Usage: stopvnc <port>
# Exit codes: 0 = success, 1 = invalid arguments, 2 = vnc server not found, 3 = stop failed

# Check if exactly 1 argument is provided
if [ $# -ne 1 ]; then
    echo "Usage: $0 <port>" >&2
    echo "Example: $0 5900" >&2
    exit 1
fi

PORT="$1"

# Validate port number
if ! [[ "$PORT" =~ ^[0-9]+$ ]] || [ "$PORT" -lt 1024 ] || [ "$PORT" -gt 65535 ]; then
    echo "Error: Port must be a number between 1024 and 65535" >&2
    exit 1
fi

# Calculate display number (VNC display = port - 5900)
DISPLAY_NUM=$((PORT - 5900))
if [ $DISPLAY_NUM -lt 0 ]; then
    echo "Error: Port must be 5900 or higher for VNC display" >&2
    exit 1
fi

# Check if VNC server is running on this display
VNC_LOCK_FILE="$HOME/.vnc/$(hostname):${DISPLAY_NUM}.pid"
if [ ! -f "$VNC_LOCK_FILE" ]; then
    # Also check if process is actually running on the port
    if ! netstat -tuln 2>/dev/null | grep -q ":$PORT "; then
        echo "No VNC server found running on port $PORT (display :$DISPLAY_NUM)" >&2
        exit 2
    fi
fi

# Try to kill VNC server gracefully
echo "Stopping VNC server on port $PORT (display :$DISPLAY_NUM)..."
vncserver -kill ":$DISPLAY_NUM"
KILL_RESULT=$?

# Check if the kill command succeeded
if [ $KILL_RESULT -eq 0 ]; then
    echo "VNC server on port $PORT stopped successfully"
    exit 0
else
    # If graceful shutdown failed, try to find and kill the process by port
    echo "Graceful shutdown failed, attempting forceful termination..."
    
    # Find process using the port
    PID=$(netstat -tulnp 2>/dev/null | grep ":$PORT " | awk '{print $7}' | cut -d'/' -f1)
    
    if [ -n "$PID" ] && [ "$PID" != "-" ]; then
        kill -TERM "$PID" 2>/dev/null
        sleep 2
        
        # Check if process is still running
        if kill -0 "$PID" 2>/dev/null; then
            # Force kill if still running
            kill -KILL "$PID" 2>/dev/null
            sleep 1
        fi
        
        # Verify the process is gone
        if ! kill -0 "$PID" 2>/dev/null; then
            echo "VNC server on port $PORT forcefully terminated"
            
            # Clean up lock file if it exists
            if [ -f "$VNC_LOCK_FILE" ]; then
                rm -f "$VNC_LOCK_FILE"
            fi
            
            exit 0
        else
            echo "Error: Failed to stop VNC server on port $PORT" >&2
            exit 3
        fi
    else
        echo "Error: Could not find process using port $PORT" >&2
        exit 2
    fi
fi