#!/bin/zsh -Ndefgku
#
# Scripts/package
# mas
#
# Builds .pkg installer.
#

. "${0:a:h}/_setup_script"

print_notice '📦 Packaging installer for' "${@}"

export MAS_DO_NOT_PRINT_NOTICE=
Scripts/build "${1:-}" -c release "${@:2}"
unset MAS_DO_NOT_PRINT_NOTICE

build_dir=.build
destination_dir="${build_dir}/destination"
mas_executable="${destination_dir}/mas"
version="$(Scripts/version)"

mkdir -p "${destination_dir}"
ln -f "$(swift build -c release --show-bin-path "${@:2}")/mas" "${mas_executable}"

pkgbuild\
 --identifier io.github.mas-cli.mas\
 --install-location /usr/local/bin\
 --version "${version}"\
 --root "${destination_dir}"\
 "${build_dir}/mas_components.pkg"

# shellcheck disable=SC1036
productbuild\
 --distribution =(cat <<'END'
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<installer-gui-script minSpecVersion="2">
	<title>mas</title>
	<pkg-ref id="io.github.mas-cli.mas">
		<bundle-version/>
	</pkg-ref>
	<pkg-ref id="io.github.mas-cli.mas" onConclusion="none">#mas_components.pkg</pkg-ref>
	<domains enable_localSystem="true" enable_anywhere="true" enable_currentUserHome="false"/>
	<options customize="never" require-scripts="false"/>
	<volume-check>
		<allowed-os-versions>
			<os-version min="10.15"/>
		</allowed-os-versions>
	</volume-check>
	<choices-outline>
		<line choice="default">
			<line choice="io.github.mas-cli.mas"/>
		</line>
	</choices-outline>
	<choice id="default"/>
	<choice id="io.github.mas-cli.mas" visible="false">
		<pkg-ref id="io.github.mas-cli.mas"/>
	</choice>
</installer-gui-script>
END
)\
 --package-path "${build_dir}"\
 "${build_dir}/mas-${version}-${${(s: :o)$(lipo -archs "${mas_executable}")}// /-}.pkg"
