#!/bin/bash
# Restricted shell for socktop webterm
# Only allows 'socktop' and 'help' commands

# Colors for output
BLUE='\033[0;34m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# History file
HISTFILE="/home/socktop/.socktop_history"
HISTSIZE=1000

# Load history from file
load_history() {
    if [ -f "$HISTFILE" ]; then
        history -r "$HISTFILE"
    fi
}

# Save history to file
save_history() {
    history -w "$HISTFILE"
}

# Welcome message
show_welcome() {
    echo -e "${MAGENTA}"
    cat << "EOF"
    ╔═══════════════════════════════════════════════════════════╗
    ║                   Welcome to socktop                      ║
    ║           A TUI-first Remote System Monitor               ║
    ╚═══════════════════════════════════════════════════════════╝
EOF
    echo -e "${NC}"
    echo -e "${CYAN}Available commands:${NC}"
    echo -e "  ${GREEN}socktop${NC}  - Launch the socktop TUI"
    echo -e "  ${GREEN}help${NC}     - Show this help message"
    echo ""
    echo -e "${YELLOW}Type 'help' for more information${NC}"
    echo ""
}

# Help message
show_help() {
    echo -e "${BLUE}╔═══════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║${NC}                     socktop Help                         ${BLUE}║${NC}"
    echo -e "${BLUE}╚═══════════════════════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "${CYAN}What is socktop?${NC}"
    echo "  socktop is a beautiful, TUI-first system monitor built with Rust."
    echo "  It allows you to monitor local and remote Linux systems in real-time"
    echo "  with an elegant terminal interface."
    echo ""
    echo -e "${CYAN}Available Commands:${NC}"
    echo ""
    echo -e "  ${GREEN}socktop${NC}"
    echo "    Launch socktop with the local profile (monitors this container)"
    echo ""
    echo -e "  ${GREEN}socktop -P <profile>${NC}"
    echo "    Launch socktop with a specific profile from profiles.json"
    echo "    Example: socktop -P rpi-master"
    echo ""
    echo -e "  ${GREEN}socktop <websocket_url>${NC}"
    echo "    Connect to a remote socktop-agent directly"
    echo "    Example: socktop ws://192.168.1.100:3000"
    echo ""
    echo -e "  ${GREEN}help${NC}"
    echo "    Show this help message"
    echo ""
    echo -e "${CYAN}Available Profiles:${NC}"
    echo "  • local         - Monitor this container (localhost:3000)"
    echo "  • rpi-master    - Raspberry Pi Master node"
    echo "  • rpi-worker-1  - Raspberry Pi Worker 1"
    echo "  • rpi-worker-2  - Raspberry Pi Worker 2"
    echo "  • rpi-worker-3  - Raspberry Pi Worker 3"
    echo ""
    echo -e "${CYAN}Keyboard Shortcuts (inside socktop):${NC}"
    echo "  q           - Quit socktop"
    echo "  Tab         - Switch between views"
    echo "  ↑/↓         - Navigate lists"
    echo "  PageUp/Down - Scroll faster"
    echo ""
    echo -e "${CYAN}Links:${NC}"
    echo "  GitHub:        https://github.com/jasonwitty/socktop"
    echo "  Documentation: https://jasonwitty.github.io/socktop/"
    echo "  Crates.io:     https://crates.io/crates/socktop"
    echo ""
    echo -e "${YELLOW}Ready to monitor? Type: ${GREEN}socktop${NC}"
    echo ""
}

# Main restricted shell loop
main() {
    # Load command history
    load_history

    # Show welcome on first run
    if [ ! -f /tmp/.socktop_welcome_shown ]; then
        show_welcome
        touch /tmp/.socktop_welcome_shown
    fi

    while true; do
        # Display prompt
        echo -ne "${GREEN}socktop${NC}@${BLUE}demo${NC} ${YELLOW}▶${NC} "

        # Read user input with readline support (enables arrow keys, history, etc.)
        read -e -r input

        # Add non-empty commands to history
        if [ -n "$input" ]; then
            history -s "$input"
            save_history
        fi

        # Trim whitespace
        input=$(echo "$input" | xargs)

        # Skip empty input
        if [ -z "$input" ]; then
            continue
        fi

        # Parse command (first word)
        cmd=$(echo "$input" | awk '{print $1}')
        args=$(echo "$input" | cut -d' ' -f2-)

        case "$cmd" in
            socktop)
                # Allow socktop with validated arguments only
                if [ "$cmd" = "$input" ]; then
                    # No arguments, use default (local profile)
                    /usr/bin/socktop -P local
                else
                    # Validate and sanitize arguments to prevent command injection
                    # Only allow: -P <profile_name> or ws://<url>

                    # Check for profile argument (-P followed by safe profile name)
                    if [[ "$args" =~ ^-P[[:space:]]+[a-zA-Z0-9_-]+$ ]]; then
                        # Extract profile name and validate it
                        profile=$(echo "$args" | sed 's/-P[[:space:]]\+//')
                        /usr/bin/socktop -P "$profile"
                    # Check for websocket URL (ws:// or wss://)
                    elif [[ "$args" =~ ^wss?://[a-zA-Z0-9\.\:/_-]+$ ]]; then
                        # Validate websocket URL format
                        /usr/bin/socktop "$args"
                    else
                        # Reject anything else as potentially dangerous
                        echo -e "${RED}Error:${NC} Invalid arguments for socktop"
                        echo -e "${YELLOW}Allowed usage:${NC}"
                        echo "  socktop              - Use default local profile"
                        echo "  socktop -P <profile> - Use named profile (alphanumeric, dash, underscore only)"
                        echo "  socktop <ws_url>     - Connect to websocket URL (ws:// or wss://)"
                        echo ""
                        echo -e "${YELLOW}Examples:${NC}"
                        echo "  socktop -P rpi-master"
                        echo "  socktop ws://192.168.1.100:3000"
                    fi
                fi
                ;;
            help|--help|-h)
                show_help
                ;;
            exit|quit|logout)
                echo -e "${YELLOW}Use Ctrl+D to exit the shell${NC}"
                ;;
            clear|cls)
                clear
                echo -e "${YELLOW}Screen cleared. Type 'help' for available commands.${NC}"
                ;;
            "")
                # Empty command, do nothing
                ;;
            *)
                # Unknown command
                echo -e "${RED}Error:${NC} Command '$cmd' is not allowed"
                echo -e "${YELLOW}Available commands:${NC} ${GREEN}socktop${NC}, ${GREEN}help${NC}"
                echo -e "Type ${GREEN}help${NC} for more information"
                ;;
        esac
    done
}

# Handle Ctrl+C gracefully
trap 'echo -e "\n${YELLOW}Use Ctrl+D to exit${NC}"; continue' INT

# Run main loop
main
