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

# =============================================================================
# Lazygit Universal Deployer & Packager
# 1. Configures modular YAML settings (Themes, Delta Pager, NVIM)
# 2. Deploys to /etc/skel or current $USER
# 3. Builds a .deb package for system-wide installation
# =============================================================================

# --- Settings ---
GITHUB_USER="jesseduffield"
PROJECT="lazygit"
BASE_THEME="mocha"  # frappe, latte, macchiato, mocha
THEME_ACCENT="blue" # blue, peach, green, etc.
MAINTAINER="${SUDO_USER:-$USER}@$(hostname)"

# --- Determine Target Directory ---
TARGET_DIR="${1:-/etc/skel}"
TARGET_DIR="${TARGET_DIR%/}"
REAL_USER="${SUDO_USER:-$USER}"
REAL_HOME=$(getent passwd "$REAL_USER" | cut -d: -f6)

echo "🎯 Target: $TARGET_DIR | User: $REAL_USER"

# --- Prep Directories ---
CONFIG_ROOT="${TARGET_DIR}/.config/lazygit"
EXTRAS_DIR="${CONFIG_ROOT}/extras"
ALIASES_D="${TARGET_DIR}/.zsh_aliases.d"

mkdir -p "$EXTRAS_DIR" "$ALIASES_D"

# --- Generate Modular Configs ---

# Theme (Catppuccin)
THEME_URL="https://raw.githubusercontent.com/catppuccin/lazygit/main/themes-mergable/${BASE_THEME}/${THEME_ACCENT}.yml"
curl -sL "$THEME_URL" -o "${EXTRAS_DIR}/00-theme.yml" || echo "⚠️ Theme download failed, skipping..."

# Editor (NVIM Remote)
cat <<EOF >"${EXTRAS_DIR}/10-editor.yml"
os:
  editPreset: 'nvim-remote'
  edit: 'if command -v nvr >/dev/null 2>&1; then nvr --remote-wait "{{filename}}"; else nvim "{{filename}}"; fi'
  editAtLine: 'if command -v nvr >/dev/null 2>&1; then nvr --remote-wait +{{line}} "{{filename}}"; else nvim +{{line}} "{{filename}}"; fi'
EOF

# Git Paging (Delta)
cat <<EOF >"${EXTRAS_DIR}/30-pager-delta.yml"
git:
  paging:
    colorArg: always
    pager: delta --dark --paging=never --line-numbers --hyperlinks
EOF

# The Zsh Alias
# This dynamically finds all .yml files and builds the LG_CONFIG_FILE string
cat <<'EOF' >"${ALIASES_D}/005_lazygit.zsh"
_gen_lg_config() {
    local base="$HOME/.config/lazygit"
    if [[ -d "$base" ]]; then
        local files=($(find "$base" -name "*.yml" | sort))
        echo "${(j:,:)files}"
    fi
}
alias lg="LG_CONFIG_FILE=\$(_gen_lg_config) lazygit"
EOF

# --- Fix Permissions ---
if [[ "$TARGET_DIR" != "/etc/skel" ]]; then
  chown -R "$REAL_USER:$REAL_USER" "$CONFIG_ROOT" "$ALIASES_D"
fi

# --- Build the .deb Package ---
echo "📦 Fetching latest Lazygit binary..."
API_JSON=$(curl -sL "https://api.github.com/repos/${GITHUB_USER}/${PROJECT}/releases/latest")
GIT_TAG=$(echo "$API_JSON" | grep -Po '"tag_name": *"\K[^"]*')
VERSION="${GIT_TAG#v}"

# Architecture Mapping
OS_NAME=$(uname -s)
OS_NAME=${OS_NAME,,}
ARCH_RAW=$(uname -m)
case "$ARCH_RAW" in
i386 | i686) LG_ARCH="x86" ;;
x86_64) LG_ARCH="x86_64" ;;
armv6*) LG_ARCH="armv6" ;;
armv7*) LG_ARCH="armv7" ;;
aarch64) LG_ARCH="arm64" ;;
*) LG_ARCH="$ARCH_RAW" ;;
esac

# Download Binary
BUILD_DIR=$(mktemp -d)
cd "$BUILD_DIR"
URL="https://github.com/${GITHUB_USER}/${PROJECT}/releases/download/${GIT_TAG}/lazygit_${VERSION}_${OS_NAME}_${LG_ARCH}.tar.gz"

curl -Lo lazygit.tar.gz "$URL"
tar -xf lazygit.tar.gz lazygit

# Build Script for Checkinstall
cat <<EOF >install.sh
#!/bin/bash
install -Dm755 lazygit /usr/local/bin/lazygit
EOF
chmod +x install.sh

echo "🛠️ Running Checkinstall..."
sudo checkinstall -y \
  --pkgname="${PROJECT}" \
  --pkgversion="${VERSION}" \
  --pkgrelease="1" \
  --pkggroup="utils" \
  --maintainer="${MAINTAINER}" \
  --provides="lazygit" \
  --requires="git,curl" \
  --nodoc --deldesc=yes --default \
  bash ./install.sh

echo "✅ Deployment complete. System-wide package installed."
