#!/bin/zsh -Ndefgku
#
# Scripts/_setup_script
# mas
#
# Copyright © 2025 mas-cli. All rights reserved.
#
# Performs boilerplate setup for scripts.
#

builtin unalias -as
setopt\
	autopushd\
	combiningchars\
	extendedglob\
	extendedhistory\
	no_globalrcs\
	histexpiredupsfirst\
	histignorespace\
	histverify\
	incappendhistorytime\
	interactivecomments\
	pipefail\
	no_rcs\
	no_unset
export HISTCHARS='!^#'
export IFS=$' \t\n\0'
export NULLCMD=cat
export PAGER=cat
export READNULLCMD=cat
export TMPDIR="${"${TMPDIR:-/tmp/}"/%(#b)([^\/])/"${match[1]}"/}"
export TMPPREFIX="${TMPPREFIX:-"${TMPDIR}"zsh}"
unset CDPATH
unset ENV
unset KEYBOARD_HACK
unset TMPSUFFIX
unset WORDCHARS

readonly mas_folder="${0:A:h:h}"
if ! cd -- "${mas_folder}"; then
	printf $'Error: Failed to cd into mas folder: %s\n' "${mas_folder}" >&2
	exit 1
fi

print_notice() {
	[[ -v MAS_DO_NOT_PRINT_NOTICE ]] && return
	if [[ -t 1 ]]; then
		local -r prefix=$'\e[1;34m==>\e[0m'
	else
		local -r prefix='==>'
	fi
	printf $'%s %s mas %s%s\n'\
		"${prefix}"\
		"${1}"\
		"${MAS_VERSION:-$(Scripts/version)}"\
		"${${*:2}:+ (arguments: ${${(q)@:2}[*]})}"
}

ensure_command_available() {
	local -i return_status=0
	local command
	for command in "${@}"; do
		if ! whence "${command}" >/dev/null; then
			printf $'error: %s is not installed. Run \'Scripts/bootstrap\' or \'brew install %s\'.\n'\
				"${command}"\
				"${command}"\
				>&2
			return_status=1
		fi
	done
	return "${return_status}"
}
