#!/bin/bash --norc
set -o pipefail
set -ef
# note: bash-dependent, see checkbashisms

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=
gitbranch=
force_rewrite=
gear_rules_restore_branches=
localgitdir=
gitery_origin=gitery
gitorigin=
gitorigin='gears'

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=d:I:J:fL:o:
LONGOPTIONS=,force,restore-branches,no-restore-branches,local-git-dir:,origin:,gitery-origin:
# 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
	-d|--localbranch|--local-git-branch)
	    gitbranch="$2"
	    readonly gitbranch
            shift 2 ;;
	-f|--force)
	    force_rewrite=-f
	    readonly force_rewrite
            shift ;;
	-J|--restore-branches)
	    gear_rules_restore_branches=yes
	    readonly gear_rules_restore_branches
            shift ;;
	--no-restore-branches)
	    gear_rules_restore_branches=
	    readonly gear_rules_restore_branches
            shift ;;
	-L|--local-git-dir)
	    localgitdir="$2"
	    readonly localgitdir
            shift 2 ;;
	-o|--origin) gitorigin="$2"
	    readonly gitorigin
            shift 2 ;;
	-I|--gitery-origin) gitery_origin="$2"
	    readonly gitery_origin
            shift 2 ;;
	-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

name="$1"
if [ -z "$name" ]; then
    pod2usage --exit=2 "$0"; exit 2;
fi
[ -z "$localgitdir" ] && localgitdir=${2:-}
[ -z "$localgitdir" ] && localgitdir="$name.git"

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

commit=`git ls-remote -h ${GITERY_HOST:-$git_default_url}:/gears/${name:0:1}/${name}.git refs/heads/$REPOSITORY_BRANCH | awk '{print $1}'`
if [ -z "$commit" ]; then
    echo "Error:$name is not a git-built package for $REPOSITORY_BRANCH. commit not found."
    otherbranches=`git ls-remote -h ${GITERY_HOST:-$git_default_url}:/gears/${name:0:1}/${name}.git | grep -E 'refs/heads/' | sed -e 's,^.*refs/heads/,,'`
    if [ -n "$otherbranches" ]; then
	echo
	echo "NOTE: If the package was removed from Sisyphus,"
	echo "and you are looking for an old build,"
	echo "the following branches are available: (-b option)"
	echo $otherbranches
    fi
    exit 1
fi

if [ -e "$localgitdir" ]; then
    if [ -n "$force_rewrite" ]; then
	rm -rf "$localgitdir"
    else
	echo "Error: $localgitdir already exists." >&2
	exit 1
    fi
fi


$DRY_RUN git clone ${gitorigin:+-o $gitorigin} \
    "${GITERY_HOST:-$git_default_url}:/gears/${name:0:1}/${name}.git" "$localgitdir"

if [ ! -d "$localgitdir" ]; then
    echo "Error: $localgitdir is not cloned!" >&2
    exit 1
fi

if [ -n "$gitbranch" ]; then
    pushd "$localgitdir"
    $DRY_RUN git branch -D "$gitbranch" 2>/dev/null ||:
    $DRY_RUN git checkout -b "$gitbranch" $commit
    popd
fi

if [ -n "$gitery_origin" ]; then
    $DRY_RUN git --git-dir="$localgitdir/.git" config 'remote.'"$gitery_origin"'.url' "${GITERY_HOST:-$gitery_default_url}:packages/$localgitdir"
    $DRY_RUN git --git-dir="$localgitdir/.git" config 'remote.'"$gitery_origin"'.push' "refs/heads/*:refs/heads/*"
    $DRY_RUN git --git-dir="$localgitdir/.git" config 'remote.'"$gitery_origin"'.fetch' "+refs/heads/*:refs/remotes/origin/*"
fi

if [ -n "$gear_rules_restore_branches" ];then
    $DRY_RUN cd  "$localgitdir" || exit 3
    $DRY_RUN gear-rules-restore-branches
fi



: <<'__EOF__'

=head1	NAME

girar-clone-build-commit - clone gitery:/gears/ repository

=head1	SYNOPSIS

B<girar-clone-build-commit>
[B<-d|--local-git-branch> I<local destination branch>]
[B<-f|--force>]
[B<-J|--restore-branches>]
[B<-L|--local-git-dir> I<local repository name>]
[B<-o|--origin> I<name>][B<-I|--gitery-origin> I<name>]
[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<name> [I<local repository name>]

=head1	DESCRIPTION

B<girar-clone-build-commit> clone gitery:/gears/../name.git repository
and place last build commit into local destination branch.

=head1	OPTIONS

=over

=item	B<-d|--localbranch|--local-git-branch> I<destination branch>

Name of the local checked out git branch. Default is master.

=item	B<-f|--force>

Forcefully remove previous <name>.git and clone over even if <name>.git already exists.

=item	B<-J|--restore-branches>

Call gear-rules-restore-branches after cloning.

=item	B<-L|--local-git-dir> I<local repository name>

The name of the local git repository to create. Default is I<name.git>.
Also it can be specified as the second argument.

=item	B<-I|--gitery-origin>=[I<remotes name>]

The name of git remote I<remotes name> that points to your remote
repository on gitery I<gitery>:packages/I<local repository name>.git.
Default is gitery.

=item	B<-o|--origin> I<remotes name>

This option is passed to git-clone. I<remotes name> is the name
of git remote for the repository we are cloning from.
By default, it is set to B<gears>
for girar-clone-build-commit and to B<task> for girar-clone-task-git.
It us to prevent git of using the remote name 'origin' to keep
track of the repository we do cloning.

=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__
