#!/bin/bash
# Helper script to start code-server in the coder container
# This script should be run as the coder user

# Check if code-server is already running and responding
if curl -s -f http://localhost:8080 >/dev/null 2>&1; then
    echo "code-server is already running"
    exit 0
fi

# Kill any zombie processes
pkill -9 code-server 2>/dev/null || true
sleep 0.5

# Apply VS Code theme from environment variable if set
# VSCODE_THEME can be 'dark' or 'light' (passed from host application)
SETTINGS_FILE="/home/coder/.local/share/code-server/User/settings.json"
if [ -n "$VSCODE_THEME" ] && [ -f "$SETTINGS_FILE" ]; then
    if [ "$VSCODE_THEME" = "light" ]; then
        THEME_NAME="Default Light+"
    else
        THEME_NAME="Default Dark+"
    fi

    # Use jq to update the colorTheme setting
    if command -v jq &> /dev/null; then
        TMP_FILE=$(mktemp)
        if jq --arg theme "$THEME_NAME" '.["workbench.colorTheme"] = $theme' "$SETTINGS_FILE" > "$TMP_FILE" 2>/dev/null; then
            mv "$TMP_FILE" "$SETTINGS_FILE"
            echo "Applied VS Code theme: $THEME_NAME"
        else
            rm -f "$TMP_FILE"
            echo "Warning: Failed to update VS Code theme"
        fi
    else
        echo "Warning: jq not available, skipping theme update"
    fi
fi

# Clean up chat/AI panel state to prevent unwanted panels from appearing
# Note: VS Code stores panel visibility in workspace storage, but we can't prevent
# the chat panel from appearing without finding the exact state file.
# Users will need to close it once per container, then it stays closed.
rm -rf /home/coder/.local/share/code-server/User/workspaceStorage/*/chatSessions 2>/dev/null || true
rm -rf /home/coder/.local/share/code-server/User/workspaceStorage/*/chatEditingSessions 2>/dev/null || true

# Ensure log directory is writable
touch /tmp/code-server.log 2>/dev/null || true

# Start code-server without authentication (security handled by proxy)
echo "Starting code-server..."
code-server --bind-addr 0.0.0.0:8080 --auth none --disable-telemetry /workspace >/tmp/code-server.log 2>&1 &

# Get PID
CODE_SERVER_PID=$!

# Wait for it to respond
for i in {1..10}; do
    if curl -s -f http://localhost:8080 >/dev/null 2>&1; then
        echo "code-server started successfully (PID: $CODE_SERVER_PID)"
        exit 0
    fi

    # Check if process is still running
    if ! kill -0 $CODE_SERVER_PID 2>/dev/null; then
        echo "code-server process died - check logs:"
        cat /tmp/code-server.log 2>/dev/null || echo "No log file"
        exit 1
    fi

    sleep 1
done

echo "code-server not responding after 10 seconds - check logs:"
cat /tmp/code-server.log 2>/dev/null || echo "No log file"
exit 1
