: ${AUTOENV_AUTH_FILE:=~/.autoenv_auth}
: ${AUTOENV_FILE_ENTER:=.autoenv.zsh}
: ${AUTOENV_FILE_LEAVE:=.autoenv_leave.zsh}
: ${AUTOENV_DISABLED:=0}
: ${AUTOENV_HANDLE_LEAVE:=1}


_autoenv_hash_pair() {
    local env_file="${1:A}"

    if [ ! -s "${env_file}" ]; then
        return 1
    fi

    local env_cksum=${${:-$(cksum "${env_file}")}[1]}
    printf "%s:%s" "${env_file}" "${env_cksum}"
}

_autoenv_envfile_authorize() {
    local env_cksum="$(_autoenv_hash_pair "${1}")"

    local line
    for line in $(<"${AUTOENV_AUTH_FILE}")
    do
        if [ "${line}" == "${env_cksum}" ]; then
            return 0
        fi
    done

    return 1
}

_autoenv_source_if_authorized() {
    local file_to_source="${1}"

    if [ ! -s "${file_to_source}" ]; then
        return 1
    fi

    if ! _autoenv_envfile_authorize "${file_to_source}"; then
        return 1
    fi

    source "${file_to_source}"
}

_autoenv() {
    _autoenv_source_if_authorized "${PWD}/${AUTOENV_FILE_ENTER}"
}

_autoenv_leave() {
    _autoenv_source_if_authorized "${OLDPWD}/${AUTOENV_FILE_LEAVE}"
}

if [[ "${AUTOENV_DISABLED}" != 1 ]]; then
    autoload -U add-zsh-hook
    add-zsh-hook chpwd _autoenv

    if [[ "${AUTOENV_HANDLE_LEAVE}" == 1 ]]; then
        add-zsh-hook chpwd _autoenv_leave
    fi

    _autoenv_source_if_authorized "${PWD}/${AUTOENV_FILE_ENTER}"
fi


autoenv-auth() {
    echo >> "${AUTOENV_AUTH_FILE}"
    if [ -s "${PWD}/${AUTOENV_FILE_ENTER}" ]; then
        _autoenv_hash_pair "${PWD}/${AUTOENV_FILE_ENTER}" >> "${AUTOENV_AUTH_FILE}"
        echo >> "${AUTOENV_AUTH_FILE}"
    fi

    if [ -s "${PWD}/${AUTOENV_FILE_LEAVE}" ]; then
        _autoenv_hash_pair "${PWD}/${AUTOENV_FILE_LEAVE}" >> "${AUTOENV_AUTH_FILE}"
        echo >> "${AUTOENV_AUTH_FILE}"
    fi
}


# vim: ft=zsh