#!/usr/bin/env bash
# =============================================================================
# Kitty + Neovim scrollback setup script (2026 style with kitty-scrollback.nvim)
# =============================================================================

set -euo pipefail

# Install base packages
sudo apt update -qq
sudo apt install -y kitty kitty-terminfo kitty-shell-integration fonts-firacode

# =============================================================================
# Paths
# =============================================================================

DEST="${1:-/etc/skel}"
KITTY_HOME="${DEST}/.config/kitty"
ALIASES_D="${DEST}/.zsh_aliases.d"
ZSHRC_D="${DEST}/.zshrc.d"
SESSIONS_D="${KITTY_HOME}/sessions"

mkdir -p "${KITTY_HOME}" "${ALIASES_D}" "${ZSHRC_D}" "${SESSIONS_D}"

ALIAS_FILE="${ALIASES_D}/003_kitty.zsh"

# =============================================================================
# 1. OpenGL detection → decide if we force software rendering
# =============================================================================

should_use_software() {
  local gl_version=""
  local es_version=""

  if command -v glxinfo >/dev/null 2>&1; then
    gl_version=$(glxinfo | grep -i "OpenGL version string" | head -n 1 | awk -F: '{print $2}' | xargs)
    if [[ "$gl_version" =~ ^([4-9]\.|3\.[3-9]) ]]; then
      return 1 # hardware ok
    fi
  fi

  if command -v eglinfo >/dev/null 2>&1; then
    es_version=$(eglinfo -B 2>/dev/null | grep -i "OpenGL ES profile version" | head -n 1 | grep -oE '[0-9]+\.[0-9]+' || true)
    if [[ "$es_version" =~ ^[3-9]\. ]]; then
      return 1 # GLES 3+ usually good enough
    fi
  fi

  return 0 # force software
}

conf_print_kitty_alias_hw() {
  cat <<'EOF' | tee "${ALIAS_FILE}"
# kitty → hardware rendering (OpenGL ≥3.3 detected)
alias kitty="kitty"
EOF
}

conf_print_kitty_alias_sw() {
  cat <<'EOF' | tee "${ALIAS_FILE}"
# kitty → software rendering (old/weak OpenGL)
alias kitty="LIBGL_ALWAYS_SOFTWARE=1 kitty"
EOF
}

if should_use_software; then
  conf_print_kitty_alias_sw
  echo "# Forced software rendering due to insufficient OpenGL support" | tee -a "${ALIAS_FILE}"
else
  conf_print_kitty_alias_hw
  echo "# Using hardware rendering" | tee -a "${ALIAS_FILE}"
fi

# =============================================================================
# 2. Common kitty aliases (only active inside kitty)
# =============================================================================

cat <<'EOF' | tee -a "${ALIAS_FILE}"

if [[ "${XTERM}" = "xterm-kitty" || -n "${KITTY_INSTALLATION_DIR}" ]]; then
    alias ssh="kitty +kitten ssh"
    alias kt="kitty +kitten transfer"
fi
EOF

# =============================================================================
# 3. kitty ssh.conf stub
# =============================================================================

confi_print_kitty_ssh() {
  cat <<'EOF'
# kitty +kitten ssh configuration

copy .zshrc
copy .vimrc
copy .vim
copy .gitconfig

# env EDITOR=nvim
# env LANG=en_US.UTF-8

# hostname build-*
#   copy ~/.ssh/config
EOF
}
confi_print_kitty_ssh | tee "${KITTY_HOME}/ssh.conf"

# =============================================================================
# 4. Example session
# =============================================================================

conf_print_sessions() {
  cat <<'EOF'
new_tab dev
    cd ~/projects
    title code
    launch zsh -c 'nvim .'
    launch zsh
    layout tall

new_tab scratch
    cd ~
    launch zsh
    layout tall
EOF
}
conf_print_sessions | tee "${SESSIONS_D}/kitty-session.conf"

# =============================================================================
# 5. Manual shell integration (tmux/containers friendly)
# =============================================================================

conf_print_zsh_int() {
  cat <<'EOF'
# Manual kitty shell integration
if [[ -n "${KITTY_INSTALLATION_DIR:-}" ]]; then
    export KITTY_SHELL_INTEGRATION="enabled"
    autoload -Uz -- "${KITTY_INSTALLATION_DIR}/shell-integration/zsh/kitty-integration"
    kitty-integration
    unfunction kitty-integration
fi
EOF
}
conf_print_zsh_int | tee "${ZSHRC_D}/002_kitty.zsh"

# =============================================================================
# 6. Main kitty.conf + kitty-scrollback.nvim integration
# =============================================================================
# See /var/tmp/020_neovim-lazyvim_plugins.sh

conf_print_kitty() {
  cat <<'EOF'
# vim:ft=kitty

# ─── Performance ─────────────────────────────────────────────────────────────
input_delay               0
repaint_delay             2
sync_to_monitor           no

# ─── Font ────────────────────────────────────────────────────────────────────
font_family               FiraCode Nerd Font
bold_font                 auto
italic_font               auto
bold_italic_font          auto
font_size                 11.5

font_features             FiraCode Nerd Font +cv04 +cv10 +ss04 +ss03 +cv25 +cv32 +cv28 +ss06 +ss07
disable_ligatures         never

# ─── Cursor / Mouse ──────────────────────────────────────────────────────────
cursor_shape              block
cursor_blink_interval     0
copy_on_select            yes
strip_trailing_spaces     always

# ─── Window ──────────────────────────────────────────────────────────────────
window_border_width       1px
hide_window_decorations   no
background_opacity        0.88

# ─── Bell ────────────────────────────────────────────────────────────────────
enable_audio_bell         no
window_alert_on_bell      yes
bell_on_tab               no

# ─── Tabs ────────────────────────────────────────────────────────────────────
tab_bar_edge              top
tab_bar_style             powerline

# ─── Updates & Integration ───────────────────────────────────────────────────
update_check_interval     0
shell_integration         disabled

# ─── Browser ─────────────────────────────────────────────────────────────────
open_url_with             default

# ─── Scrollback (modern 2026 style with kitty-scrollback.nvim) ───────────────
scrollback_lines          20000
scrollback_pager_history_size 4

# Required for kitty-scrollback.nvim remote control
# allow_remote_control      yes
allow_remote_control      socket-only
listen_on                 unix:/tmp/kitty-remote

# Recommended mappings
map ctrl+shift+question   kitty_scrollback_nvim --config search

## nvim --headless +'KittyScrollbackGenerateKittens'
# kitty-scrollback.nvim Kitten alias
action_alias kitty_scrollback_nvim kitten /home/default/.local/share/nvim/lazy/kitty-scrollback.nvim/python/kitty_scrollback_nvim.py

# Browse scrollback buffer in nvim
map kitty_mod+h kitty_scrollback_nvim

# Browse output of the last shell command in nvim
map kitty_mod+g kitty_scrollback_nvim --config ksb_builtin_last_cmd_output
 
# Show clicked command output in nvim
mouse_map ctrl+shift+right press ungrabbed combine : mouse_select_command_output : kitty_scrollback_nvim --config ksb_builtin_last_visited_cmd_output

## /

# Mouse: right-click under cursor → last command output
# mouse_map ctrl+shift+right press ungrabbed combine : mouse_select_command_output : kitty_scrollback_nvim --config last_cmd

# ─── Theme stub ──────────────────────────────────────────────────────────────
# BEGIN_KITTY_THEME
include current-theme.conf
# END_KITTY_THEME
EOF
}
conf_print_kitty | tee "${KITTY_HOME}/kitty.conf"

# =============================================================================
# 7. A few example themes
# =============================================================================

conf_print_nord_theme() {
  cat <<'EOF'
foreground #d8dee9
background #2e3440
selection_foreground #d8dee9
selection_background #434c5e
cursor #d8dee9
cursor_text_color #2e3440
url_color #88c0d0
active_border_color #88c0d0
inactive_border_color #4c566a
color0  #3b4252
color1  #bf616a
color2  #a3be8c
color3  #ebcb8b
color4  #81a1c1
color5  #b48ead
color6  #88c0d0
color7  #e5e9f0
color8  #4c566a
color9  #bf616a
color10 #a3be8c
color11 #ebcb8b
color12 #81a1c1
color13 #b48ead
color14 #8fbcbb
color15 #eceff4
EOF
}
conf_print_nord_theme | tee "${KITTY_HOME}/Nord.conf"

conf_print_macchiato_theme() {
  cat <<'EOF'
foreground #cad3f5
background #24273a
selection_foreground #24273a
selection_background #f4dbd6
cursor #f4dbd6
url_color #f4dbd6
active_border_color #b7bdf8
inactive_border_color #6e738d
color0  #494d64
color1  #ed8796
color2  #a6da95
color3  #eed49f
color4  #8aadf4
color5  #f5bde6
color6  #8bd5ca
color7  #b8c0e0
color8  #5b6078
color9  #ed8796
color10 #a6da95
color11 #eed49f
color12 #8aadf4
color13 #f5bde6
color14 #8bd5ca
color15 #a5adcb
EOF
}
conf_print_macchiato_theme | tee "${KITTY_HOME}/Catppuccin-Macchiato.conf"

# =============================================================================
# Final message
# =============================================================================

cat <<'EOF'

Kitty configuration written.

Next steps:
  1. Make sure kitty-scrollback.nvim is installed in lazyvim
  2. Restart kitty or source your shell
  3. Test scrollback with ctrl+shift+h
  4. Change theme interactively:   kitty +kitten themes
  5. Optional: run in Neovim :KittyScrollbackCheckHealth

Enjoy!

EOF
