#!/usr/bin/env bash

set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

export PATH="$HOME/.local/share/nvim/mason/bin:$PATH"

require_cmd() {
  command -v "$1" >/dev/null 2>&1 || {
    printf 'Required validation tool not found: %s\n' "$1" >&2
    exit 1
  }
}

for command in bash git nvim shellcheck shfmt starship stylua wezterm zsh; do
  require_cmd "$command"
done

shell_files=(bin/dotfiles-apply-theme bin/check-dotfiles install/install.sh install/lib/*.sh)

git diff --check
bash -n "${shell_files[@]}"
zsh -n .zshrc
git config --file .gitconfig --list >/dev/null
shellcheck --exclude=SC1091 "${shell_files[@]}"
shfmt -d -i 2 -ci "${shell_files[@]}"
stylua --check .config/nvim

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
mkdir -p "$tmp/data/nvim"
ln -s "$HOME/.local/share/nvim/lazy" "$tmp/data/nvim/lazy"

HOME="$tmp/home" \
  KANAGAWA_THEME=wave \
  WEZTERM_FONT_SIZE=13 \
  WEZTERM_WINDOW_OPACITY=.9 \
  WEZTERM_TEXT_OPACITY=1 \
  bin/dotfiles-apply-theme

STARSHIP_CONFIG="$repo_root/.config/starship/starship.toml" starship print-config >/dev/null
STARSHIP_CONFIG="$repo_root/.config/starship/starship-wave.toml" starship print-config >/dev/null
wezterm --config-file "$repo_root/.config/wezterm/wezterm.lua" show-keys --lua >/dev/null

nvim_output="$(
  DOTFILES_CI=1 \
    XDG_CONFIG_HOME="$repo_root/.config" \
    XDG_CACHE_HOME="$tmp/cache" \
    XDG_DATA_HOME="$tmp/data" \
    XDG_STATE_HOME="$tmp/state" \
    nvim --headless '+sleep 100m' '+lua assert(vim.v.errmsg == "", vim.v.errmsg)' '+qa' 2>&1
)"
if [[ -n $nvim_output ]]; then
  printf 'Neovim startup produced unexpected output:\n%s\n' "$nvim_output" >&2
  exit 1
fi

printf 'All dotfile checks passed.\n'
