#!/usr/bin/env zsh
setopt NO_GLOBAL_RCS NO_GLOBAL_EXPORT NO_RCS

# Log functions [[[
function error(){ print -P "%F{red}[ERROR]%f: ${1}" && return 1; }
function info() { print -P "%F{green}[INFO]%f:%F{cyan} ${1} %f"; }
function warn() { print -P "%F{yellow}[WARN]%f: ${1}"; }
# ]]]
# Create Zunit test environment [[[
GIT_REPO=$(git rev-parse --show-toplevel)

_mktemp_cmd='mktemp'
if (( ${+commands[gmktemp]} )); then
    _mktemp_cmd='gmktemp'
fi
TMP_ZUNIT=$(${_mktemp_cmd} --directory --tmpdir="${GIT_REPO}/tests/_support")
if [[ ! -d ${TMP_ZUNIT} ]]; then
    error "zunit temp dir not found"
    exit 1
fi

typeset -gAH ZINIT;
ZINIT[HOME_DIR]=${TMP_ZUNIT};
ZINIT[BIN_DIR]=$ZINIT[HOME_DIR]/zinit.git;
ZINIT[COMPLETIONS_DIR]=$ZINIT[HOME_DIR]/completions;
ZINIT[PLUGINS_DIR]=$ZINIT[HOME_DIR]/plugins;
ZINIT[SNIPPETS_DIR]=$ZINIT[HOME_DIR]/snippets;
ZINIT[ZCOMPDUMP_PATH]=$ZINIT[HOME_DIR]/zcompdump;
ZPFX=$ZINIT[HOME_DIR]/polaris;

command git diff > ${ZINIT[HOME_DIR]}/unstaged.diff
info 'creating test env'
git clone \
    --depth=1 \
    --dissociate \
    --no-hardlinks \
    --reference "${GIT_REPO}" \
    file://${GIT_REPO:A} \
    "${ZINIT[BIN_DIR]}"
if (( $? != 0 )); then
    error "Unable to copy ${GIT_REPO} to ${TMP_ZUNIT}" >&2
    exit 1
fi

if [[ -s $ZINIT[HOME_DIR]/unstaged.diff ]]; then
    (
        git -C $ZINIT[BIN_DIR] apply $ZINIT[HOME_DIR]/unstaged.diff && \
            chmod g-rwX "${ZINIT[HOME_DIR]}" && \
            zcompile "${ZINIT[BIN_DIR]}/zinit.zsh"
    )
fi
(( $? != 0 )) && { error "Unable to copy ${GIT_REPO} to ${TMP_ZUNIT}" >&2; exit 1 }

source $ZINIT[BIN_DIR]/zinit.zsh
(( $? != 0 )) && { error "Unable to copy ${GIT_REPO} to ${TMP_ZUNIT}" >&2; exit 1 }
# ]]]
# Install Annexes [[[
info 'installing test dependencies'
for annex (binary-symlink default-ice); do
  if [[ ! -d ${GIT_REPO}/tests/_support/$annex ]]; then;
    git clone https://github.com/zdharma-continuum/zinit-annex-$annex ${GIT_REPO:A}/tests/_support/$annex
  fi
  zinit light ${GIT_REPO:A}/tests/_support/$annex
  info "loaded $annex dependencies"
done
# ]]]

# vim:ft=zsh:sw=2:sts=2:et:foldmarker=[[[,]]]:foldmethod=marker
