#!/bin/sh -ef

export LC_ALL=C
verbose=
OPTIONS=
LONGOPTIONS=
REPOSITORY_BRANCH="sisyphus"
# alt system gits
git_default_url=git://git.altlinux.org
# alt system web shared tasks
web_default_tasks_url=http://git.altlinux.org
WEBERY_HOST=
WEB_TASKS_URL=
# alt personal gits
gitery_default_url=git://gitery.altlinux.org
gitery_default_host=
GITERY_HOST=
GIRAR_HOST=
DRY_RUN=
TASKID=
BEFORE_SUBTASK=
add_to_task=
build_task=
case $0 in *-task-add*) add_to_task=1;; *girar-build-*) build_task=1;; esac;
TASK_SHARE=
task_deps=
TASK_RUN_HURRY=
TASK_RUN_UNHURRY=
TASK_RUN_TEST_ONLY=
TASK_RUN_FAIL_LATE=
girar_message=

for config_file in /etc/girar-nmu/default ${XDG_CONFIG_HOME:-$HOME/.config}/girar-nmu/default; do
    ! [ -e "$config_file" ] || . "$config_file"
done
# --- autodetection in absence of config file ---
if [ -z "$gitery_default_host" ]; then
    if grep -E '^Host[[:space:]]+gitery[[:space:]]*$' ~/.ssh/config >/dev/null; then
	gitery_default_host=gitery
    elif grep -E '^Host[[:space:]]+git.alt[[:space:]]*$' ~/.ssh/config >/dev/null; then
	gitery_default_host=git.alt
    else
	gitery_default_host=gitery
    fi
fi
if [ -z "$GIRAR_HOST" ]; then
    if grep -E '^Host[[:space:]]+girar[[:space:]]*$' ~/.ssh/config >/dev/null; then
	GIRAR_HOST=girar
    elif grep -E '^Host[[:space:]]+gyle[[:space:]]*$' ~/.ssh/config >/dev/null; then
	GIRAR_HOST=gyle
    elif grep -E '^Host[[:space:]]+gyle.alt[[:space:]]*$' ~/.ssh/config >/dev/null; then
	GIRAR_HOST=gyle.alt
    elif grep -E '^Host[[:space:]]+sborochnitsa[[:space:]]*$' ~/.ssh/config >/dev/null; then
	GIRAR_HOST=sborochnitsa
    else
	GIRAR_HOST=girar
    fi
fi
# --- end autodetection ---------------------------


OPTIONS=a:AB:''SD:m:O
LONGOPTIONS=,add,add-to-task:,task:,before:,before-subtask:,deps:,share,no-share,fail-early,fail-late,hurry,no-hurry,unhurry,no-test-only,test-only,message:,gm:,gyle-message:,girar-message:
# not compatible with set -e
#getopt --test > /dev/null; #if [ "$?" -ne 4 ]; then
if getopt --test > /dev/null; then
    echo "Oops! `getopt --test` not failed. Bad getopt!." >&2
    exit 1
fi
__OPTS=hqVvb:H:P:R:
__LONGOPTS=dry-run,help,quiet,verbose,version,branch:,girar:,gyle:,gitery:,git.alt:,profile:,webery:,web_tasks_url:
PARSED=$(getopt --options=$__OPTS$OPTIONS --longoptions=$__LONGOPTS$LONGOPTIONS --name "$0" -- "$@")
if [ "$?" -ne 0 ]; then
    exit 2
fi
eval set -- "$PARSED"

while true; do
    case "$1" in
	-a|--add-to-task|--task) TASKID="$2"
	    add_to_task=1
	    readonly TASKID
            shift 2 ;;
	-A|--add)
	    TASKID=
	    add_to_task=1
	    readonly TASKID
	    shift ;;
	-B|--before|--before-subtask) BEFORE_SUBTASK="$2"
	    readonly BEFORE_SUBTASK
            shift 2 ;;
	-D|--deps) task_deps="$2"
            shift 2 ;;
	--no-share) TASK_SHARE=
            shift ;;
	-S|--share) TASK_SHARE=1
            shift ;;

	--gm|--girar-message|gyle-message) girar_message="$2"
	    girar_message=${girar_message// /_}
            shift 2 ;;
	-m|--message) girar_message="$2"
	    echo "WARINING: option -m (--message) is ambiguous. Assuming --girar-message">&2;
	    echo "Please, use --gm (--girar-message), --cm (--commit-message), --tm (--tag-message).">&2
	    girar_message=${girar_message// /_}
	    shift 2 ;;
	--test-only) TASK_RUN_TEST_ONLY=--test-only
            shift ;;
	-O|--no-test-only) TASK_RUN_TEST_ONLY=
            shift ;;
	--fail-late) TASK_RUN_FAIL_LATE=1
            shift ;;
	--fail-early) TASK_RUN_FAIL_LATE=
            shift ;;
	--no-hurry) TASK_RUN_HURRY=
            shift ;;
	--unhurry) TASK_RUN_UNHURRY=1
		TASK_RUN_HURRY=
            shift ;;
	--hurry) TASK_RUN_HURRY=1
		TASK_RUN_UNHURRY=
            shift ;;
	-P|--profile)
	    local profile_file="$2"
	    for config_file in /etc/girar-nmu/"$profile_file" ${XDG_CONFIG_HOME:-$HOME/.config}/girar-nmu/"$profile_file"; do
		! [ -e "$config_file" ] || . "$config_file"
	    done
            shift 2 ;;
        -q|--quiet)
            verbose=
            shift ;;
        -V|--version)
            echo "2.015.2"
	    exit 0
            shift ;;
        -v|--verbose)
            verbose=$(($verbose+1))
            shift ;;
	-h|--help)
	    pod2usage --exit=0 "$0";
	    exit 0 ;;
	-b|--branch)
	    REPOSITORY_BRANCH="$2"
	    readonly REPOSITORY_BRANCH
            shift 2 ;;
	-H|--gitery|--git.alt)
	    GITERY_HOST="$2"
	    readonly GITERY_HOST
            shift 2 ;;
	-R|--girar|--gyle)
	    GIRAR_HOST="$2"
	    readonly GIRAR_HOST
            shift 2 ;;
	-W|--webery)
	    WEBERY_HOST="$2"
	    readonly WEBERY_HOST
            shift 2 ;;
	--web-tasks-url)
	    WEB_TASKS_URL="$2"
	    readonly WEB_TASKS_URL
            shift 2 ;;
        --dry-run)
            DRY_RUN=echo
            shift ;;
        --)
            shift
            break
            ;;
        *)
	    echo "Internal error: Unexpected option: $1 $2" >&2
	    #pod2usage --exit=3 "$0"
            exit 3
            ;;
    esac
done

girar_action=rebuild
case $0 in
    *-rebuild*)
	girar_action=rebuild
	: ${girar_message:=rebuild}
		;;
    *-del*)
	girar_action=del
	: ${girar_message:=deleted}
	    ;;
    *-copy*)
	girar_action=copy
	: ${girar_message:=backport}
	;;
esac

if [ -n "$BEFORE_SUBTASK" ] && [ -z "$TASKID" ]; then
    echo "-B|--before <before_subtask_id> require -a|--task <taskid> option" >&2
    exit 2
fi

[ 0"$verbose" -ge 3 ] && set -x ||:

RETVAL=0
task_options_applied=
apply_task_properties()
{
    if [ -n "$TASK_SHARE" ] && [ $RETVAL -eq 0 ]; then
	$DRY_RUN ssh $GIRAR_HOST task share $TASKID enable || RETVAL=$?
    fi
    if [ -n "$task_deps" ] && [ $RETVAL -eq 0 ]; then
	for dep in `perl -e 'map {print $_, " " } split(",",$ARGV[0])' $task_deps`; do
	    $DRY_RUN ssh $GIRAR_HOST task deps $TASKID add $dep || RETVAL=$?
	done
    fi
    task_options_applied=1
    return $RETVAL
}

task_do_girar_action()
{
    local first_arg second_arg task_add_prefix
    first_arg=$1
    second_arg="$2"
    task_add_prefix=${3:-}
    if [ -n "$add_to_task" ]; then
	$DRY_RUN ssh $GIRAR_HOST task add $TASKID $BEFORE_SUBTASK $task_add_prefix $first_arg "$second_arg"
	[ -n "$task_options_applied" ] || apply_task_properties
    elif [ -n "$TASK_SHARE" ]; then
	$DRY_RUN ssh $GIRAR_HOST task new ${REPOSITORY_BRANCH:+$REPOSITORY_BRANCH}
	$DRY_RUN ssh $GIRAR_HOST task add $TASKID $BEFORE_SUBTASK $task_add_prefix $first_arg "$second_arg"
	apply_task_properties
	$DRY_RUN ssh "$GIRAR_HOST" task run ${TASK_RUN_TEST_ONLY:---commit} ${TASK_RUN_HURRY:+--hurry} ${TASK_RUN_UNHURRY:+--unhurry} ${TASK_RUN_FAIL_LATE:+--fail-late} ${girar_message:+-m "$girar_message"} "$TASKID"
    else
	$DRY_RUN ssh $GIRAR_HOST build ${REPOSITORY_BRANCH:+-b $REPOSITORY_BRANCH} ${TASK_RUN_TEST_ONLY:---commit} ${TASK_RUN_HURRY:+--hurry} ${TASK_RUN_UNHURRY:+--unhurry} ${TASK_RUN_FAIL_LATE:+--fail-late} ${task_deps:+--deps $task_deps} ${girar_message:+-m "$girar_message"} $first_arg "$second_arg"
    fi
}


if [ -n "$build_task" ] && [ -z "$TASKID" ] && [ -z "$add_to_task" ]; then
    add_to_task=1
    $DRY_RUN ssh $GIRAR_HOST task new ${REPOSITORY_BRANCH:+$REPOSITORY_BRANCH}
fi


for name in "$@"; do
    task_do_girar_action $girar_action "$name"
done

if [ -n "$build_task" ]; then
    $DRY_RUN ssh "$GIRAR_HOST" task run ${TASK_RUN_TEST_ONLY:---commit} ${TASK_RUN_HURRY:+--hurry} ${TASK_RUN_UNHURRY:+--unhurry} ${TASK_RUN_FAIL_LATE:+--fail-late} ${girar_message:+-m "$girar_message"} "$TASKID"
fi


: <<'__EOF__'

=head1	NAME

girar-task-add-rebuild - add "rebuild <name>" commands.
girar-task-add-copy - add "copy <name>" commands.
girar-task-add-del - add "del <name>" commands.

=head1	SYNOPSIS

B<>
[B<-a|--add-to-task|--task> I<task ID>]
[B<-A|--add>]
[B<-B|--before|--before-subtask> I<before_subtask_id>]
[B<-D|--deps> I<comma separated list>]
[B<-S|--share>]
[B<--gm|--girar-message|--gyle-message> I<message>]
[B<-O|--no-test-only>]
[B<--test-only>]
[B<--unhurry>]
[B<--hurry>]
[B<--fail-early|--fail-late>]
[B<-H|--gitery> I<ssh gitery alias>]
[B<-R|--girar> I<ssh girar(gule) alias>]
[B<-W|--webery> I<tasks web site>]
[B<--web-tasks-url> I<tasks web site url>]
[B<-b|--branch> I<repository>]
[B<--dry-run>]
[B<-P|--profile> I<profile>]
[B<-h|--help>]
[B<-v|--verbose>]
[B<-q|--quiet>]

I<srpm ...>

=head1	DESCRIPTION

B<girar-task-add-rebuild>, B<girar-task-for-each-rebuild>, B<girar-build-rebuild>,
B<girar-task-add-copy>, B<girar-task-for-each-copy>, B<girar-build-copy>,
B<girar-task-add-del>, B<girar-task-for-each-del>, B<girar-build-del>,
add "rebuild <name>", "copy <name>" or "del <name>" commands
to the default or given task, or create and run new task(s) in prescribed order.

The scripts differ in their default behaviour depending on their name.
B<girar-task-add-*> add the arguments to the specified or to the last task,
B<girar-task-for-each-*> create and run separate tasks for each argument,
B<girar-build-*> create and run the arguments in one big task.

=head1	OPTIONS

=over

=item  Add to task options.

=over

=item	B<-a|--add-to-task|--task> [I<task ID>]

Specifies the girar task to add.
Also enables "task add" mode, see below.

=item	B<-A|--add>

Enables "task add" mode. In this mode, the argument(s) are added
to the current or the specified task. This disables "for each" mode
and stops "build" mode from creating a separate task.

=item	[B<-B|--before|--before-subtask> I<before_subtask_id>]

I<before_subtask_id> is used in the extended format of girar-task add command:
girar-task add [<task_id> [<before_subtask_id>]] srpm <filename>

=back


=item  Run task options.

=over

=item	B<-D|--deps> I<dep1,...,depN>

Comma separated list of task dependencies to add.

=item	B<-S|--share>

Create and run a shared task. Disabled by default.
Also, B<--no-share> disables it.


=item	B<--gm|--girar-message|--gyle-message> I<message>

Specifies a girar task message.

=item	B<--test-only>

Run task --test-only

=item	B<--commit|-O|--no-test-only>

Do not run task --test-only (default).

=item	B<--hurry>

Run task with --hurry (undocumented girar option)

=item	B<--no-hurry>

Remove --hurry from run command line,
B<--no-hurry> option does not set --unhurry.

=item	B<--unhurry>

Run task with --unhurry (undocumented girar option)

=item	B<--fail-early>

Stop building the task after the first error.

=item	B<--fail-late>

Do not stop building the task after the first error.

=back


=item	B<-b|--branch> I<repository branch>

Name of the repository branch. Values: sisyphus|p8|..
Default is sisyphus.

=item	B<-R|--girar> I<girar(gyle) ssh alias>

By default, gyle.altlinux.org account should be configured as girar or gyle in ~/.ssh/config.
If you do not follow that convention, use -R <your girar ssh alias> option.

=item	B<-H|--gitery> I<gitery ssh alias>

Alternative gitery or ssh alias for gitery, for example, git.e2k.
If not specified, by default, gitery is used where ssh account is
required and git.altlinux.org is used where http:// is enough.

=item	B<-W|--webery> I<tasks web site>

Alternative site that hosts girar tasks.
If not specified, by default, git.altlinux.org is used.

=item	[B<--web-tasks-url> I<tasks web site url>]

The default URL for web task site is http://I<tasks web site>.
See --webery for details. B<--web-tasks-url> overrides this URL.

=item	B<--dry-run>

Echo state-changing commands instead of doing them. An extra safety.
Also a bit useful for debugging.

=item	B<-P|--profile> I<profile>

Name of the configuration profile. The profile is loaded as
/etc/girar-nmu/I<profile> and $HOME/.config/girar-nmu/I<profile>.
Note that default configuration is stored in
/etc/girar-nmu/default and $HOME/.config/girar-nmu/default.

=item	B<-V|--version>

Print version and exit.

=item	B<-v|--verbose>

Verbose. Prints extra information. Multiple -v accumulate.
-v -v -v set debug mode (set -x).

=item	B<-q|--quiet>

Quiet. Print no warnings.

=item	B<-h|--help>

Display this help and exit.


=back

=head1	AUTHOR

Written by Igor Vlasenko <viy@altlinux.org>.

=head1	COPYING

Copyright (c) 2010-2022 Igor Vlasenko, ALT Linux Team.

This is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.

=cut

__EOF__
