#!/usr/bin/env bash

set -o nounset

tmpdir=$(mktemp -d)
trap 'rm -rf $tmpdir' EXIT
trap 'echo ; exit -2' INT

# Start from the base yadm directory
cd "$(dirname "${BASH_SOURCE[0]}")" || exit_with_error "Failed to find yadm directory!"
cd .. || exit_with_error "Failed to find yadm directory!"

if [[ "$YADM_HOOK_FULL_COMMAND" =~ (^| )(--no-verify|-n)($| ) ]]; then
    # Same as `git commit --no-verify`
    exit 0
fi

# shellcheck source=../utils.sh
source utils.sh

# skip checks for merge commits:
if is_merging; then
    exit 0
fi

WARNINGS=0

# Check for unstaged changes (typically new functions/completions or config files)
CHECK_UNTRACKED_DIRS=(
    # ~/.config/fish/
    ~/.config/thefuck/
)
untracked_files=$(
    yadm ls-files --full-name --exclude-standard --others -- "${CHECK_UNTRACKED_DIRS[@]}"
)
if [[ $untracked_files ]]; then
    exit_with_error "Untracked files found in repository:" "$untracked_files"
fi

if grep -E 'path = /|submodule "/' -- ~/.gitmodules; then
    exit_with_error "Submodule paths in $HOME/.gitmodules should be relative!"
fi

# TODO: needs a `shared_secret` to work properly. Also a post-pull hook to
# import the preset again would be handy, see also
# https://community.folivora.ai/t/syncing-the-config-in-git/34840/4?u=ianchamberlain
# osascript -e 'tell application "BetterTouchTool"
#     export_preset outputPath "~/.config/btt/Default.bttpreset" includeSettings true
# end tell'

if [ $WARNINGS -gt 0 ]; then
    read -r -p "Some pre-commit checks had warnings. Press enter to continue or Ctrl-C to cancel."
fi

# It's also possible to run pre-commit directly here, but it doesn't
# play as nicely with the automatic stashing/staging stuff vs a normal githook.

# TODO: Convert the remainder of this stuff to pre-commit, if feasible. For brew,
# maybe just switch to nix instead and do a `darwin-rebuild check` or something
