#!/bin/sh -efu

TOP="$(readlink -ev .)"

. kernel-build-sh-functions

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

print_version()
{
	cat <<EOF
$PROG version $PROG_VERSION

Copyright (C) 2012 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
}


show_help()
{
	cat <<EOF
$PROG - create tags on kernel-module templates

Usage: $PROG [options] <flavour> <module> [<module>...]
   or: $PROG [options] -k <flavour> [-k <flavour>...] <module> [<module>...]

Options:
  -a, --arches=MODULE_ARCHES  module ExclusiveArch;
  -d, --distribution=NAME     distribution branch name (alt-linux-X.Y);
  -f, --force                 pass -f to gear-create-tag(1);
  -k, --kernel=FLAVOUR        kernel flavour;
  -V, --version               print program version and exit;
  -h, --help                  show this text and exit.

EOF
	exit
}

TEMP=`getopt -n "$PROG" -o a:,d:,f,k:,V,h -l arches:,distribution:,force,kernel:,version,help -- "$@"` ||
	show_usage
eval set -- "$TEMP"

opt_force=
opt_distribution=sisyphus
opt_kernels=
opt_karch="%ix86 x86_64"
while :; do
	case "$1" in
		--) shift; break
			;;
		-a|--arches) shift; opt_karch="$1"
			;;
		-d|--distribution) shift; opt_distribution="$1"
			;;
		-f|--force) opt_force='-f'
			;;
		-k|--kernel) shift; opt_kernels="$opt_kernels $1"
			;;
		-V|--version) print_version
			;;
		-h|--help) show_help
			;;
		*) fatal "Unrecognized option: $1"
			;;
	esac
	shift
done

if [ -z "$opt_kernels" ]; then
	[ $# -ge 1 ] || show_usage "Not enough arguments"
	opt_kernels="$1" && shift
fi

[ $# -ge 1 ] || show_usage "Not enough arguments"
modules="$*"

mkdir -p out

for kernel in $opt_kernels; do
	for module in $modules; do
		set - $(gear --describe --disable-specsubst -t template/$module/$opt_distribution)

		name=${1%%-@*}; shift
		version=$1; shift
		release=${1%%.%*}; shift

		[ -n "$name" -a -n "$version" -a -n "$release" ] ||
			fatal "failed to obtain module NVR"

		tagname="$opt_distribution/kernel-modules-$module-$kernel-$version-$release"

		gear-create-tag $opt_force -n "$tagname" -m "kernel-modules-$module-$kernel $version-$release
X-gear-specsubst: kflavour=$kernel
X-gear-specsubst: karch=$opt_karch" \
			template/$module/$opt_distribution
		echo "$tagname" >> out/taglist
	done
done
