#!/usr/bin/env zsh
# Tests for the zshrc and functions. Uses a throwaway HOME; touches nothing of yours.
emulate -L zsh
setopt err_return no_unset pipe_fail
ROOT=${0:A:h:h}
TMP=$(mktemp -d)
trap 'rm -rf $TMP' EXIT
fails=0
ok()   { print -P "%F{green}ok%f   $1" }
fail() { print -P "%F{red}FAIL%f $1"; (( fails++ )) || true }
check() { local name=$1; shift; if "$@" >/dev/null 2>&1; then ok $name; else fail $name; fi }

# 1. Syntax
check 'zshrc parses' zsh -n $ROOT/zshrc
check 'zshenv parses' zsh -n $ROOT/zshenv
for f in $ROOT/functions/*; do
  check "functions/${f:t} parses" zsh -n $f
done

# 2. Full interactive startup in a clean HOME (no plugins installed)
mkdir -p $TMP/home
ln -s $ROOT/zshrc $TMP/home/.zshrc
out=$(HOME=$TMP/home ZDOTDIR=$TMP/home XDG_STATE_HOME=$TMP/home/.local/state \
      XDG_CACHE_HOME=$TMP/home/.cache XDG_DATA_HOME=$TMP/home/.local/share \
      zsh -i -c 'print -r -- "$HISTFILE|$(alias gs)|${+functions[plug-install]}|$(whence -w mkcd)"' 2>&1)
[[ $out == *"/.local/state/zsh/history|gs='git status -sb'|1|mkcd: function"* ]] && ok 'interactive startup' || fail "interactive startup: $out"
[[ $out != *"command not found"* && $out != *"no such file"* ]] && ok 'startup has no errors' || fail "startup errors: $out"

# 3. Functions
fpath=($ROOT/functions $fpath)
autoload -Uz $ROOT/functions/*(N.:t)
cd $TMP

mkcd a/b/c && [[ $PWD == $TMP:A/a/b/c || $PWD == $TMP/a/b/c ]] && ok mkcd || fail mkcd
up 2 && [[ ${PWD:t} == a ]] && ok 'up 2' || fail 'up 2'
cd $TMP/a/b/c && up a && [[ ${PWD:t} == a ]] && ok 'up <name>' || fail 'up <name>'
cd $TMP
up nonexistent-dir 2>/dev/null && fail 'up bad name' || ok 'up bad name returns error'

mkdir -p src && print hello > src/file.txt
tar -czf pkg.tar.gz src && rm -rf src
extract pkg.tar.gz && [[ $(<src/file.txt) == hello ]] && ok 'extract tar.gz' || fail 'extract tar.gz'
extract missing.zip 2>/dev/null && fail 'extract missing' || ok 'extract missing returns error'

b=$(bak src/file.txt) && [[ -f $b && $b == src/file.txt.*.bak ]] && ok bak || fail bak

print 0 > counter
bump() { local n=$(<counter); print $(( n + 1 )) > counter; (( n + 1 >= 3 )) }
retry -n 5 -d 0 bump 2>/dev/null && [[ $(<counter) == 3 ]] && ok 'retry succeeds on 3rd try' || fail retry
retry -n 2 -d 0 false 2>/dev/null && fail 'retry gives up' || ok 'retry gives up'

[[ $(calc '7 / 2') == 3.5* ]] && ok calc || fail "calc: $(calc '7 / 2')"
[[ $(calc 'sqrt(16)') == 4.* ]] && ok 'calc mathfunc' || fail 'calc mathfunc'

[[ $(print '{"a":1}' | json) == *'"a": 1'* ]] && ok json || fail json

print
(( fails == 0 )) && print "all tests passed" || { print "$fails test(s) failed"; exit 1 }
