#!/bin/bash
#
# VCradle Shell Wrapper
# This script sets up the environment and launches the locked shell
#

# Set up logging
export VCRADLE_SHELL_LOG="/var/log/vcradle-shell.log"

# Ensure log directory exists
mkdir -p /var/log

# Set up environment
export PYTHONPATH="/vcradle:$PYTHONPATH"
export PATH="/vcradle/app/system:$PATH"

# Check if running as root or if we need sudo for privileged operations
if [[ $EUID -eq 0 ]]; then
    SUDO_CMD=""
else
    SUDO_CMD="sudo"
fi

# Set terminal title
echo -ne "\033]0;VCradle System Console\007"

# Clear screen and start the shell
clear

# Log shell access
echo "$(date): VCradle shell accessed by $(whoami) from $(tty)" >> "$VCRADLE_SHELL_LOG"

# Launch the Python shell with proper error handling
cd /vcradle
python3 /vcradle/app/system/locked_shell.py

# If the shell exits with an error, fall back to a minimal emergency shell
if [ $? -ne 0 ]; then
    echo "VCradle shell encountered an error. Starting emergency mode..."
    echo "$(date): Emergency shell mode activated for $(whoami)" >> "$VCRADLE_SHELL_LOG"

    # Simple emergency menu
    while true; do
        clear
        echo "================================"
        echo "   VCRADLE EMERGENCY MODE"
        echo "================================"
        echo ""
        echo "1. View system status"
        echo "2. Check network connectivity"
        echo "3. Restart network services"
        echo "4. Launch bash (root only)"
        echo "5. Reboot system"
        echo "6. Exit"
        echo ""
        read -p "Choose option (1-6): " choice

        case $choice in
            1)
                echo "System status:"
                uptime
                free -h
                df -h
                read -p "Press Enter to continue..."
                ;;
            2)
                echo "Testing network connectivity..."
                ping -c 3 8.8.8.8
                read -p "Press Enter to continue..."
                ;;
            3)
                echo "Restarting network services..."
                $SUDO_CMD systemctl restart systemd-networkd
                $SUDO_CMD systemctl restart systemd-resolved
                $SUDO_CMD netplan apply
                echo "Network services restarted"
                read -p "Press Enter to continue..."
                ;;
            4)
                if [[ $EUID -eq 0 ]]; then
                    echo "Starting bash shell..."
                    bash
                else
                    echo "Root access required for bash shell"
                    read -p "Press Enter to continue..."
                fi
                ;;
            5)
                echo "Rebooting system..."
                $SUDO_CMD reboot
                ;;
            6)
                exit 0
                ;;
            *)
                echo "Invalid option"
                read -p "Press Enter to continue..."
                ;;
        esac
    done
fi