#!/bin/bash
# Script: startvnc
# Purpose: Start TigerVNC server with specified password and port
# Usage: startvnc <port>
# Exit codes: 0 = success, 1 = invalid arguments, 2 = vnc setup failed, 3 = vnc start failed

# Check if exactly 1 argument is provided
if [ $# -ne 1 ]; then
    echo "Usage: $0 <port>" >&2
    echo "Example: $0 5901" >&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 1 ]; then
    echo "Error: Port must be 5901 or higher for VNC display" >&2
    exit 1
fi

# Create VNC directory if it doesn't exist
VNC_DIR="$HOME/.vnc"
mkdir -p "$VNC_DIR"

# Create xstartup file if it doesn't exist
XSTARTUP_FILE="$VNC_DIR/xstartup"
if [ ! -f "$XSTARTUP_FILE" ]; then
    cat > "$XSTARTUP_FILE" << 'EOF'
#!/bin/sh

unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS

[ -f ~/.Xresources ] && xrdb ~/.Xresources
xsetroot -solid grey
vncconfig -iconic &

# Start Xfce4 desktop
if type startxfce4 >/dev/null 2>&1; then
    startxfce4
elif type xfce4-session >/dev/null 2>&1; then
    xfce4-session
fi
EOF
    chmod +x "$XSTARTUP_FILE"
fi

# Kill any existing VNC server on this display
vncserver -kill ":$DISPLAY_NUM" 2>/dev/null || true

# Start VNC server (remove -passwd parameter as password file is already set)
vncserver ":$DISPLAY_NUM" -PlainUsers=$USER -pam_service=login -SecurityTypes=TLSPlain
if [ $? -ne 0 ]; then
    echo "Error: Failed to start VNC server on port $PORT (display :$DISPLAY_NUM)" >&2
    exit 3
fi

# Verify the server is running
sleep 2
if ! netstat -ln | grep -q ":$PORT "; then
    echo "Warning: VNC server may not be listening on port $PORT" >&2
fi

echo "VNC server started successfully on port $PORT (display :$DISPLAY_NUM)"
echo "Password file: $VNC_DIR/passwd"