#!/bin/sh
# 2017 (c) Etersoft https://etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/functions/common
load_mod git

set_girar_host $1 && shift

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
	echo "gitask ssh gear.alt task wrapper"
	echo "Use: gitask [GIRAR] [task|show|ls|quota]"
	echo "$HELP_GIRAR"
	echo "     --help - help"
	docmd ssh $GEARHOST task help | sed -e "s|abort|cancel|g"
	exit 0
fi

get_last()
{
	ssh $GEARHOST task ls | head -n1 | sed -e "s|^#\([0-9]*\) .*|\1|g" || fatal
}

# TODO: acl

epm assure girar-show girar-utils

if [ "$1" = "get" ] ; then
	if [ "$1 $2" = "get subtask" ] ; then
		[ -n "$3" ] || fatal "get subtask TASK PROJECTNMAE"
		# get subtask number from TASKNUMBER for PROJECTNAME
		SUBTASK="$(GIT_ALT=$GEARHOST girar-show $3@ | grep "/$4.git" | sed -e "s|.*#\([0-9]*\) .*|\1|g")" || fatal
		#"
		echo "$SUBTASK"
		exit
	elif [ "$1 $2 $3" = "get last " ] || [ "$1 $2 $3" = "get last task" ] ; then
		TASK="$(get_last)" || fatal
		echo "$TASK"
		exit
	else
		fatal "Unknown command $1 $2"
	fi
fi

if [ "$1" = "find" ] ; then
	shift
	#showcmd "$GEARHOST>" find-packages "$@"
	docmd ssh $GITHOST find-package "$@"
	exit
fi

if [ "$1" = "show" ] ; then
	shift
	# TODO: show last task without args
	showcmd "$GEARHOST>" girar-show "$@"
	GIT_ALT=$GEARHOST girar-show "$@"
	exit
fi

if [ "$1" = "ls" ] ; then
	shift
	if [ "$1" = "--all" ] ; then
		ssh $GEARHOST task ls "$@"
		exit
	fi
	# TODO: with arg(s) — subtask
	# TODO: add support ls -a (with subtasks)
	showcmd "$GEARHOST>" girar-show "$@"
	GIT_ALT=$GEARHOST girar-show "$@"
	exit
fi

if [ "$1" = "quota" ] ; then
	docmd ssh $GEARHOST quota
	exit
fi

if [ "$1" = "cancel" ] ; then
	shift
	#TASK="$(get_last)" || fatal
	docmd ssh $GEARHOST task abort "$@"
	exit
fi


if [ "$1" = "task" ] ; then
	# by default
	shift
fi

docmd ssh $GEARHOST task "$@"

