# vim: ft=zsh
if [[ $1 == info ]]; then
	STAGE_ALPINE_DOWN_DIR=$FSB_DOWNLOADS_DIR/alpine/
	STAGE_ALPINE_DOWN_DIR+=$STAGE_ALPINE_RELEASE/main/
	STAGE_ALPINE_DOWN_DIR+=$STAGE_ALPINE_ARCH

	mkdir -p $STAGE_ALPINE_DOWN_DIR || die "could not make download directory"
	(
		cd $STAGE_ALPINE_DOWN_DIR && \
		wget -S -N -v $FSB_ALPINE_MIRROR/$STAGE_ALPINE_RELEASE/main/$STAGE_ALPINE_ARCH/APKINDEX.tar.gz && \
		tar xf APKINDEX.tar.gz DESCRIPTION
	) || die "downloading APKINDEX failed"
	STAGE_APKINDEX_VERSION=$(<$STAGE_ALPINE_DOWN_DIR/DESCRIPTION)

	FSB_INFO_BASE=$FSB_BUILD_DIR/alpine
	FSB_INFO_BASE+=-$STAGE_ALPINE_ARCH
	FSB_INFO_BASE+=-$STAGE_ALPINE_RELEASE
	FSB_INFO_BASE+=-$STAGE_APKINDEX_VERSION
	FSB_INFO_DIR=%s-init

	return
elif [[ $1 != build ]]; then
	die "unimplemented action: $*"
fi

if ! (($+STAGE_ALPINE_REPOSITORIES)); then
	typeset -ga STAGE_ALPINE_REPOSITORIES
	STAGE_ALPINE_REPOSITORIES=( main testing )
fi

local -a apk_args
local repo
apk_args=( )

mkdir -p $build_dir/etc/apk || die "failed to set up apk"

for repo in $STAGE_ALPINE_REPOSITORIES; do
	print -rl - "$FSB_ALPINE_MIRROR/$STAGE_ALPINE_RELEASE/$repo" >> ${build_dir}/etc/apk/repositories || die "failed to set up apk"
	apk_args+=(
		--repository $FSB_ALPINE_MIRROR/$STAGE_ALPINE_RELEASE/$repo
	)
done

apk_args+=(
	#--repository file://${STAGE_ALPINE_DOWN_DIR:h:a}
	#--repository $FSB_ALPINE_MIRROR/$STAGE_ALPINE_RELEASE/main
	#--repository $FSB_ALPINE_MIRROR/$STAGE_ALPINE_RELEASE/testing
	--update-cache
	--root $build_dir
	--arch $STAGE_ALPINE_ARCH
	--keys-dir /etc/apk/keys/
	--initdb
	add alpine-base
)
apk.static $apk_args || die "alpine init failed"