#!/bin/bash
# 2003-2009 Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain

# $1 - needed VERSION of etersoft-build-utils. f.i. 162

# for systems without realpath command
realpath()
{
        readlink -f "$@"
}

# Выводит указанное сообщение об ошибке и завершает программу
fatal()
{
	if [ -z "$TEXTDOMAIN" ] ; then
		echo "Error in $0: $@" >&2
	else
		echog "Error in $0: $@" >&2
	fi
	exit 1
}

# Выводит указанное сообщение
warning()
{
	if [ -z "$TEXTDOMAIN" ] ; then
		echo "Warning in $0: $@" >&2
	else
		echog "Warning in $0: $@" >&2
	fi
}

set_eterbuilddir()
{
	[ -z "$ETERBUILDDIR" ] || return 0

	if dirname $0 | grep "^/usr" >/dev/null ; then
		ETERBUILDETC=/etc/eterbuild
		ETERBUILDDIR=/usr/share/eterbuild
	else
		# if run from no system installation
		# TODO: use real root dir not script dirname
		[ -n "$TOPDIR" ] || TOPDIR=../
		ATOPDIR=`dirname $0`/$TOPDIR
		ETERBUILDDIR=$(realpath $ATOPDIR/share/eterbuild)
		ETERBUILDETC=$(realpath $ATOPDIR/etc)
		if [ -r "$ETERBUILDETC/../AUTHORS" ] ; then
			if [ -n "$VERBOSE" ] ; then
				echo "Note: run from source tree, datadir=$ETERBUILDDIR, sysconfdir=$ETERBUILDETC"
			fi
		else
			warning "Cannot find source tree root in source tree mode"
			ETERBUILDETC=/etc/eterbuild
			ETERBUILDDIR=/usr/share/eterbuild
		fi
	fi
	ETERBUILDBIN=$(realpath $ETERBUILDDIR/../../bin)
	test -n "$ETERBUILDDIR" && PATH=$ETERBUILDDIR/functions/commands:$PATH
	# returns test result
}

# check for needed commands
#for i in distr_vendor realpath ; do
#	which $i >/dev/null || fatal
#done

# set if empty and check it
if ! set_eterbuilddir ; then
	echo "Can't detect package files location" >&2
	exit 1
fi

DISTRVENDOR=$(realpath $ATOPDIR/../rpm-build-altlinux-compat/bin/distr_vendor 2>/dev/null)
[ -x "$DISTRVENDOR" ] || DISTRVENDOR=distr_vendor

print_list()
{
	local i
	for i in $@ ; do
		echo "    $i"
	done
}


get_root_git_dir()
{
        local DIR="$1"
        [ -n "$DIR" ] || DIR=$(pwd)
        [ "$DIR" = "/" ] && return 1
        [ "$DIR" = "$HOME" ] && return 1
        if [ -d "$DIR/.git" ] ; then
                readlink -f "$DIR" 2>/dev/null || realpath "$DIR"
                return
        fi
        get_root_git_dir $(dirname "$DIR") || return 1
}

# Usage: is_gear [path_to_spec|dir_inside_git]
is_gear()
{
	local DIR="$1"
	[ -z "$IGNOREGEAR" ] || return 1
	[ -f "$DIR" ] && DIR=$(dirname "$DIR")
	local GITDIR=$(get_root_git_dir "$DIR")
	[ -d "$GITDIR/.gear" ] && return 0
	[ -r "$GITDIR/.gear-rules" ] && return 0
	return 1
}

filter_gear_name()
{
	sed -e "s|\+|plus|g"
}

# FIXME: use in rpmbs, fix for package name from spec
get_gear_name()
{
	local gitdir=$(get_root_git_dir)
	[ -n "$gitdir" ] || return
	basename "$gitdir" | filter_gear_name
}


if [ "$UID" = "0" ] && [ -z "$ALLOW_ROOT_USER" ] ; then
	fatal "It is strict recommended do not use these scripts as root"
fi

load_mod()
{
	local i
	for i in $@ ; do
		. $ETERBUILDDIR/functions/$i
	done
}

load_mod config gettext alt spec strings


# check for needed version
if [ -n "$NEEDETERBUILD" ] ; then
	if [ "$NEEDETERBUILD" -gt "$ETERBUILDVERSION" ] ; then
		echo "Obsoleted version $ETERBUILDVERSION of etersoft-build-utils version is used. Please upgrade it to $NEEDETERBUILD version."
		exit 1
	fi
fi

# Internal
detect_target_env()
{
local DISTRNAME=$($DISTRVENDOR -e)
MENVARG=""
TARGET=$($DISTRVENDOR -p)
VENDOR=$($DISTRVENDOR -s)
RPMVENDOR=$($DISTRVENDOR -n)

if [ "$VENDOR" = "alt" ] && [ -n "$MENV" ] ; then
	#[ -n "$APTCONF" ] && fatal "Internal error: APTCONF already defined as $APTCONF for $MENV"
	APTCONF=${APTCONFBASE/.SS}.$MENV
	
	[ -n "$VERBOSE" ] && echog "Target ALT Linux system: `get_altdistr_version $MENV`, use \$APTCONF"
	MENVARG="-$MENV"
else
	# FIXME: echog breaks vars
	echog "Distribution: \$DISTRNAME (\$VENDOR) (target package: \$TARGET)"
fi
}

# Отделяет файлы в LISTNAMES (с полными путями)
# Отделяет указание среды в MENV
# Устанавливает LISTARGS в оставшиеся аргументы
# использование:
# - отделяем среду (MENV)
# - отделяем файлы
# - оставшееся обрабатываем как параметры программы
parse_cmd_pre()
{
local i
if [ $# -lt 1 ]; then
    [ -n "$Usage" ] && echog "$Usage"
	fatal "Use -h for help."
fi

[ "$1" = "--help" ] && mygetopts -h

if is_gear ; then
	# Set target according to current branch
	set_target_type $(get_type_by_current_branch)
fi

LISTNAMES=
LISTARGS=
OPTINDEX=1
for i in "$@"
do
	# Если файл существует, то добавляем, иначе считаем аргумент параметром.
	if [ -f "$i" ]; then
		# echo is workaround for missed readlink
		LISTNAMES="$LISTNAMES $(readlink -f "$i" 2>/dev/null || realpath "$i" || echo "$i")"
	else
		# set target type if -M?? in param
		set_target_type ${i/-/} || LISTARGS="$LISTARGS $i"
	fi
done
LISTNAMES=$(strip_spaces "$LISTNAMES")
LISTARGS=$(strip_spaces "$LISTARGS")
# parse MENV
detect_target_env
[ -n "$VERBOSE" ] && echo "LISTNAMES=$LISTNAMES LISTARGS=$LISTARGS" || :
}

parse_cmd_pre_spec()
{
	[ "$1" = "--help" ] && mygetopts -h

	# hack for check spec or src.rpm presence in command line: skip spec detecting
	if echo $@ | grep -q \.spec || echo $@ | grep -q \.src.rpm ; then
		parse_cmd_pre "$@"
        else
		local SPEC=$(get_gear_spec)
		[ -f "$SPEC" ] && echo "Using autodetected spec $SPEC..."
		parse_cmd_pre $SPEC "$@"
	fi
}

check_ssh_key()
{
	echog "Check access to SSH private key..."
	ssh-add -l || ssh-add $SSH_KEYFILE || return 1
	return 0
}

# for backward compatibility
check_key()
{
	check_ssh_key
}

make_temp_file()
{
	# Workaround about broken mktemp
	if mktemp -V >/dev/null 2>/dev/null ; then
		mktemp || exit 1
	else
		mktemp /tmp/$1.XXXXXX || exit 1
	fi
}

# check if path is server:/path
is_ssh_target()
{
	echo "$1" | grep -q ":"
}

enable_ccache()
{
	which ccache >/dev/null || fatal "Install ccache package before using"

	# handled in gcc-common
	export GCC_USE_CCACHE=1
	# step to gcc-common
	export CC=gcc CXX=g++

	#export CC="ccache gcc"
	#export CPP="ccache gcc -E"
	#export CXX="ccache g++"
	#export CXXCPP="ccache g++ -E"

}


# If DISPLAY is broken
check_display()
{
	local XSET=$(which xset 2>/dev/null)
	[ -n "$XSET" ] || return
	$XSET -b
}
