#!/bin/bash

# =========================================================
# НАСТРОЙКА: Поменяй под конкретную ВМ
# =========================================================
MY_USER="alt"
INSTALL_CMD="apt-get"   # apt-get | dnf | yum | pacman -S --noconfirm
# =========================================================

if [ "$EUID" -ne 0 ]; then
    echo "Ошибка: Запусти через sudo!"
    exit 1
fi

# ─────────────────────────────────────────────────────────
echo "--- [1/4] Установка пакетов ---"
# ─────────────────────────────────────────────────────────
if [[ "$INSTALL_CMD" == apt* ]]; then
    $INSTALL_CMD update && $INSTALL_CMD install -y tmux nano
else
    $INSTALL_CMD install -y tmux nano
fi

# ─────────────────────────────────────────────────────────
echo "--- [2/4] Настройка Serial Console (GRUB) ---"
# ─────────────────────────────────────────────────────────
if ! grep -q "console=ttyS0" /etc/default/grub; then
    sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="\(.*\)"/GRUB_CMDLINE_LINUX_DEFAULT="\1 console=tty0 console=ttyS0,115200"/' /etc/default/grub
    
    if command -v update-grub &> /dev/null; then
        update-grub
    elif [ -f /boot/grub2/grub.cfg ]; then
        grub2-mkconfig -o /boot/grub2/grub.cfg
    elif [ -f /boot/efi/EFI/fedora/grub.cfg ]; then
        grub2-mkconfig -o /boot/efi/EFI/fedora/grub.cfg
    fi
fi

# ─────────────────────────────────────────────────────────
echo "--- [3/4] Автологин ($MY_USER) ---"
# ─────────────────────────────────────────────────────────
mkdir -p /etc/systemd/system/serial-getty@ttyS0.service.d
cat > /etc/systemd/system/serial-getty@ttyS0.service.d/autologin.conf <<'GETTY'
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin MY_USER_PLACEHOLDER --keep-baud 115200,57600,38400,9600 %I $TERM
GETTY

# Заменяем плейсхолдер на реального юзера
sed -i "s/MY_USER_PLACEHOLDER/$MY_USER/g" /etc/systemd/system/serial-getty@ttyS0.service.d/autologin.conf

systemctl daemon-reload
systemctl enable --now serial-getty@ttyS0.service 2>/dev/null

# ─────────────────────────────────────────────────────────
echo "--- [4/4] Внедрение конфигов (.bashrc, .tmux.conf, .nanorc) ---"
# ─────────────────────────────────────────────────────────
USER_HOME=$(eval echo "~$MY_USER")

for HOME_DIR in "$USER_HOME" "/root"; do
    [ ! -d "$HOME_DIR" ] && continue
    
    # 1. Очистка старых настроек
    sed -i '/# --- SMART_CONSOLE_START ---/,/# --- SMART_CONSOLE_END ---/d' "$HOME_DIR/.bashrc"

    # 2. Вставка чистого конфига (QUOTED HEREDOC — ничего не раскрывается!)
    cat <<'BASHRC_BLOCK' >> "$HOME_DIR/.bashrc"
# --- SMART_CONSOLE_START ---
# Managed by SmartConsole setup script. Do not remove markers!

# Prompt colors (red for root, green for user)
if [ "$(id -u)" -eq 0 ]; then UC='\[\e[1;31m\]'; else UC='\[\e[1;32m\]'; fi
WHITE='\[\e[1;37m\]'; BLUE='\[\e[1;34m\]'; RESET='\[\e[0m\]'
export TERM=xterm-256color
alias ls='ls --color=auto'
PS1="${WHITE}[${UC}\u${WHITE}@${UC}\h ${BLUE}\W${WHITE}]${UC}\$ ${RESET}"

# Terminal resize function (called by Chrome Extension after xterm.js loads)
res() {
    local old rows cols
    old=$(stty -g)
    stty raw -echo min 0 time 5
    printf '\0337\033[r\033[999;999H\033[6n\0338' > /dev/tty
    IFS='[;R' read -r _ rows cols _ < /dev/tty
    stty "$old"
    stty cols "$cols" rows "$rows"
}

# Auto-attach to tmux on ttyS0 (only if not already inside tmux)
if [[ $- == *i* ]] && [ -t 0 ] && [ -z "$TMUX" ] && [[ $(tty) == *ttyS0* ]]; then
    SESSION="default"
    # Create session if it doesn't exist
    tmux has-session -t "$SESSION" 2>/dev/null || tmux new-session -s "$SESSION" -d
    # Attach (extension will send 'res' after xterm.js connects)
    exec tmux attach-session -t "$SESSION"
fi

# Optional: bash syntax highlighting
BPATH=$(find /usr/share -name "bash-syntax-highlighting.bash" 2>/dev/null | head -n 1)
[ -n "$BPATH" ] && source "$BPATH"
# --- SMART_CONSOLE_END ---
BASHRC_BLOCK

    # 3. tmux config (no status bar, mouse support, fast escape)
    cat > "$HOME_DIR/.tmux.conf" <<'TMUX_CONF'
set -g status off
set -g mouse on
set -s escape-time 0
set -g default-terminal "xterm-256color"
# Don't auto-resize to smallest client
set -g aggressive-resize off
TMUX_CONF

    # 4. nano config (mouse support)
    echo "set mouse" > "$HOME_DIR/.nanorc"
    
    # 5. Fix permissions
    CURRENT_OWNER=$(basename "$HOME_DIR")
    if [ "$CURRENT_OWNER" == "root" ]; then
        chown root:root "$HOME_DIR/.bashrc" "$HOME_DIR/.tmux.conf" "$HOME_DIR/.nanorc"
    else
        chown "$MY_USER:$MY_USER" "$HOME_DIR/.bashrc" "$HOME_DIR/.tmux.conf" "$HOME_DIR/.nanorc"
    fi
done

echo ""
echo "✅ Setup complete! Reboot the VM to apply GRUB changes."
echo "   After reboot, the serial console will auto-attach to tmux."
echo "   The Chrome Extension will handle terminal resizing."