#!/bin/sh -efu
#
# Copyright (C) 2022  Gleb Fotengauer-Malinovskiy <glebfm@altlinux.org>
# All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-or-later
#

. shell-error
. shell-quote

PROG="${0##*/}"
PROG_VERSION=0.1.0

show_usage()
{
	[ -z "$*" ] || message "$*"
	echo "Try \`$PROG --help' for more information." >&2
	exit 1
}

show_help()
{
	cat <<-EOF
	Usage: $PROG -- <program> [args]

	Options:
	  -v,--version       print program version and exit;
	  -h,--help          show this text and exit.
	  --aptconf          apt config path;
	  --vm-run           use vm-run to build the image;
	  --no-vm-run        run image build on host;

	Report bugs to https://bugzilla.altlinux.org/

	EOF
	exit
}

print_version()
{
	cat <<-EOF
	$PROG version $PROG_VERSION
	Written by Gleb Fotengauer-Malinovskiy <glebfm@altlinux.org>

	Copyright (C) 2022  Gleb Fotengauer-Malinovskiy <glebfm@altlinux.org>
	This is free software; see the source for copying conditions.  There is NO
	warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
	EOF
	exit
}

TEMP=$(getopt -n $PROG -o v,h -l aptconf:,vm-run,no-vm-run,version,help -- "$@") ||
	show_usage
eval set -- "$TEMP"

aptconf="$HOME"/apt/apt.conf
run_vm=

while :; do
	case "$1" in
		-h|--help) show_help
			;;
		-v|--version) print_version
			;;
		--aptconf) shift; aptconf="$1" ;;
		--vm-run) run_vm=1 ;;
		--no-vm-run) run_vm=0 ;;
		--) shift; break
			;;
	esac
	shift
done

[ "$#" -ge 1 ] || show_usage 'Insufficient arguments.'

tmpdir=
cleanup_tmpdir()
{
	[ -z "$tmpdir" ] || rm -rf -- "$tmpdir"
	exit "$@"
}

tmpdir=$(mktemp -dt "${0##*/}.XXXXXXXX")
trap 'cleanup_tmpdir $?' EXIT
trap 'exit 143' HUP INT QUIT PIPE TERM

if [ -z "$run_vm" ]; then
	run_vm=1
	for g in $(id -nG 2>/dev/null); do
		if [ "$g" = hashman ]; then
			run_vm=0
			break
		fi
	done
fi

if [ "$run_vm" = 1 ]; then
	mounts="$(awk '{printf "%s ", $2}' /proc/mounts)"

	cat >"$tmpdir"/build-script <<-@@@
	#!/bin/sh -efu

	workdir="\$1"; shift

	cd "\$workdir"
	tmpdir="\$(mktemp -dt "mki-build.XXXXXXXX")"
	ln -snf "\$tmpdir" build
	export BUILDDIR="$PWD/build"
	branch="\$(rpm --eval %_priority_distbranch)"
	if [ -n "\$branch" ]; then
		export BRANCH="\$branch"
	fi
	export APTCONF="$aptconf"
	$(for n; do printf %s "\"$(quote_shell "$n")\" "; done)
	@@@
	chmod +x "$tmpdir"/build-script

	cat >"$tmpdir"/vm-script <<-@@@
	#!/bin/sh -efu

	workdir="\$PWD"

	/usr/share/mki-build/prepare-vm $mounts

	su -l builder -c ""$tmpdir"/build-script "\$workdir""
	@@@
	chmod +x "$tmpdir"/vm-script

	VM_RUN=vm-run
	"$VM_RUN" --sbin --rootfs --mem=max "$tmpdir"/vm-script
else
	export APTCONF="$aptconf"
	"$@"
fi
