#!/usr/bin/env bash
set -euo pipefail

readonly SCRIPT_VERSION="1.0.0"

readonly C_RESET='\033[0m'
readonly C_RED='\033[0;31m'
readonly C_GREEN='\033[0;32m'
readonly C_YELLOW='\033[0;33m'
readonly C_CYAN='\033[0;36m'

info() { echo -e "${C_CYAN}[*] $1${C_RESET}"; }
success() { echo -e "${C_GREEN}[OK] $1${C_RESET}"; }
warn() { echo -e "${C_YELLOW}[WARN] $1${C_RESET}"; }
error() { echo -e "${C_RED}[FAIL] $1${C_RESET}" >&2; exit 1; }

if [[ "$(id -u)" -ne 0 ]]; then
  command -v sudo >/dev/null 2>&1 || error "sudo is required when running as a non-root user."
  SUDO="sudo"
else
  SUDO=""
fi

echo -e "${C_CYAN}=================================================${C_RESET}"
echo -e "${C_GREEN}       Minimal Zsh install and config v${SCRIPT_VERSION}       ${C_RESET}"
echo -e "${C_CYAN}=================================================${C_RESET}"

[[ -f /etc/os-release ]] || error "Cannot detect OS because /etc/os-release is missing."
. /etc/os-release

case "${ID:-}" in
  debian|ubuntu)
    success "Detected system: ${PRETTY_NAME:-$ID}"
    ;;
  *)
    if [[ "${ID_LIKE:-}" != *debian* && "${ID_LIKE:-}" != *ubuntu* ]]; then
      error "Only Debian and Ubuntu based systems are supported."
    fi
    success "Detected Debian-compatible system: ${PRETTY_NAME:-$ID}"
    ;;
esac

info "Installing zsh and lightweight zsh integrations..."
$SUDO apt-get update
$SUDO apt-get install -y zsh zsh-common zsh-autosuggestions zsh-syntax-highlighting

ZSH_PATH="$(command -v zsh)"
ZSHRC="${HOME}/.zshrc"
MARKER_START="# >>> bitfennec zsh managed block start <<<"
MARKER_END="# >>> bitfennec zsh managed block end <<<"

touch "$ZSHRC"

if grep -qF "$MARKER_START" "$ZSHRC"; then
  sed -i "/$(printf '%s' "$MARKER_START" | sed 's/[\/&]/\\&/g')/,/$(printf '%s' "$MARKER_END" | sed 's/[\/&]/\\&/g')/d" "$ZSHRC"
fi

info "Writing minimal zsh configuration..."
cat >> "$ZSHRC" <<'EOF'

# >>> bitfennec zsh managed block start <<<
export EDITOR=vim
export PATH="$HOME/.local/bin:$HOME/.fzf/bin:$HOME/.atuin/bin:$PATH"

HISTFILE="$HOME/.zsh_history"
HISTSIZE=10000
SAVEHIST=10000

setopt append_history
setopt share_history
setopt hist_ignore_dups
setopt hist_reduce_blanks
setopt autocd

autoload -Uz compinit
mkdir -p "$HOME/.cache/zsh"
compinit -C -d "$HOME/.cache/zsh/zcompdump"

command -v starship >/dev/null 2>&1 && eval "$(starship init zsh)"
command -v zoxide >/dev/null 2>&1 && eval "$(zoxide init zsh)"
command -v atuin >/dev/null 2>&1 && eval "$(atuin init zsh --disable-up-arrow)"
if command -v fzf >/dev/null 2>&1 && fzf --zsh >/dev/null 2>&1; then
  source <(fzf --zsh)
elif [ -f "$HOME/.fzf.zsh" ]; then
  source "$HOME/.fzf.zsh"
fi

[ -f /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh ] && source /usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh
[ -f /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ] && source /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

[ -f "$HOME/.config/modern-cli/aliases.zsh" ] && source "$HOME/.config/modern-cli/aliases.zsh"
# >>> bitfennec zsh managed block end <<<
EOF

success "Zsh configuration updated: $ZSHRC"

CURRENT_SHELL="$(getent passwd "$USER" | awk -F: '{print $7}')"
if [[ "$CURRENT_SHELL" != "$ZSH_PATH" ]]; then
  echo ""
  warn "Current default shell is not zsh."
  read -r -p "Set zsh as the default shell? [y/N]: " SET_DEFAULT_SHELL
  if [[ "$SET_DEFAULT_SHELL" =~ ^[Yy]$ ]]; then
    if ! grep -qxF "$ZSH_PATH" /etc/shells; then
      echo "$ZSH_PATH" | $SUDO tee -a /etc/shells >/dev/null
    fi
    $SUDO chsh -s "$ZSH_PATH" "$USER"
    success "Default shell changed to zsh. Re-login is required."
  else
    info "Skipped default shell change."
  fi
else
  success "Zsh is already the default shell."
fi

echo ""
success "Done."
echo "Current zsh version: $($ZSH_PATH --version)"
echo "Run 'exec zsh' to enter the new shell immediately."
