#!/bin/sh

# Exit immediately if a command exits with a non-zero status
set -e

# Ensure the script is run as root
if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root (or via sudo)."
    exit 1
fi

# ==========================================
# Initialization & Banner
# ==========================================
printf "=================================================================\n"
printf "Starting Debian Linux environment setup...\n"
printf "Basic tools will be installed first. Press Ctrl+C at any time to quit.\n"
printf "=================================================================\n\n"

# ==========================================
# Package Installation (Basic)
# ==========================================
echo "--> Updating package lists..."
apt-get update

echo "--> Installing core packages (nano, zsh, curl, git)..."
# Note: oh-my-zsh is typically installed per-user via curl, 
# but we will install the base zsh requirements here.
apt-get install -y nano zsh curl git passwd

# Change default shell to zsh for the current user who called sudo
if [ -n "$SUDO_USER" ]; then
    chsh -s /bin/zsh "$SUDO_USER"
else
    chsh -s /bin/zsh
fi

# ==========================================
# Zsh Configuration (/etc/zsh/zshrc)
# ==========================================
echo "--> Writing Zsh configuration..."

# Ensure the directory exists
mkdir -p /etc/zsh

# Create file or append to it in one single block
cat << 'EOF' >> /etc/zsh/zshrc

# --- Aliases ---
alias e='nano'

# --- Prompt Configuration ---
PROMPT="%n@%m %~ %# "

EOF

# ==========================================
# Optional Package Installation (Docker)
# ==========================================
printf "\nDo you want to install Docker? (y/n): "
read -r response

case "$response" in
    [yY][eE][sS]|[yY]) 
        echo "--> Installing and configuring Docker..."
        apt-get install -y docker.io docker-compose
        
        # Enable and start Docker service using systemd
        systemctl enable docker
        systemctl start docker
        
        # If run via sudo, add the original user to the docker group
        if [ -n "$SUDO_USER" ]; then
            usermod -aG docker "$SUDO_USER"
            echo "--> Added $SUDO_USER to the docker group. You may need to relog for this to take effect."
        fi
        ;;
    *)
        echo "--> Skipping Docker installation."
        ;;
esac

# ==========================================
# Environment Handover
# ==========================================
echo "\n================================================================="
echo "Setup complete! Switching your current session to Zsh..."
echo "================================================================="

# Replaces current sh script process with Zsh to cleanly load the new config
# If running as sudo, this drops back to the user environment with zsh
if [ -n "$SUDO_USER" ]; then
    exec su - "$SUDO_USER"
else
    exec zsh -l
fi