#!/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:
  -d, --distribution=NAME     distribution branch name (alt-linux-X.Y);
  -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 d:,k:,V,h -l distribution:,kernel:,version,help -- "$@"` ||
        show_usage
eval set -- "$TEMP"

opt_distribution=sisyphus
opt_kernels=
while :; do
        case "$1" in
                --) shift; break
                        ;;
                -d|--distribution) shift; opt_distribution="$1"
                        ;;
                -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 "AAAAAA!"

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

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