#!/bin/sh -efu

. girar-sh-functions

PROG=girar-build

usage()
{
	echo >&2 "$PROG: $*"
	echo >&2 "usage: $PROG <path to git repository> <tag name> <binary package repository name> [<project name>]"
	exit 1
}

[ "$#" -ge 3 ] ||
	usage 'Not enough arguments.'
[ "$#" -le 4 ] ||
	usage 'Too many arguments.'

[ -n "${GIRAR_USER:-}" ] || 
	fatal "GIRAR_USER undefined"

cd "$HOME"

dir0="$1"; shift
dir="${dir0#$PWD/}"
[ "${dir#/}" = "$dir" ] ||
	fatal "$dir0: path to git repository does not belong to allowed directory tree"

dir="$(validate_packages_dir "$dir")"
dir="$(add_git_suffix "$dir")"
[ -d "$dir" ] ||
	fatal "$dir0: directory not available"

[ -z "${dir%%packages/*}" ] ||
	fatal "$dir0: directory should belong to packages/ directory tree"

cd "$dir"

tag_name="$1"; shift
GIT_DIR=. git rev-parse --symbolic --tags |fgrep -xqse "$tag_name" ||
	fatal "$tag_name: invalid tag name"
tag_id="$(git rev-parse --verify "$tag_name")"
GIT_DIR=. GNUPGHOME=/usr/lib/alt-gpgkeys git verify-tag "$tag_id" ||
	fatal "$tag_name: invalid tag"

repository="$1"; shift
[ -n "$repository" ] &&
printf %s "$repository" |egrep -qs '^[A-Za-z0-9][A-Za-z0-9_-.]+$' ||
	fatal "$repository: invalid binary package repository name"

if [ $# -gt 0 ]; then
	project_name="$1"; shift
else
	project_name="${PWD##*/}"
	project_name="${project_name%.git}"
fi
[ -n "$project_name" ] &&
printf %s "$project_name" |egrep -qs "$project_name_regexp" ||
	fatal "$project_name: invalid project name"

girar-check-perms "$project_name" "$repository" ||
	fatal "permission denied"

echo "$GIRAR_USER $project_name $PWD $tag_name $tag_id $repository" |
	girar-queue-task
