#!/bin/bash
# 2003-2008, 2012, 2015 (c) Etersoft www.etersoft.ru
# Author: Vitaly Lipatov <lav@etersoft.ru>
# Public domain

load_mod git hasher

is_alt()
{
	test -f /etc/altlinux-release
	return $?
}

# Internal
set_target_type()
{
	# check for M51 and so on
	if echo "$1" | egrep -q "^M[0-9][0-9].?$" ; then
		MENV="$1"
		return 0
	fi
	case "$1" in
		("DD" | "SS" | "EE")
			MENV="$1"
			return 0;
			;;
	esac
	return 1;
}

# no output if not detected
get_type_by_git_branch_name()
{
        # like p5
        if echo $1 | egrep -q "^[ptc][0-9].?$" ; then
                get_altdistr_mod $1
                return
        fi

        # like cert6
        if echo $1 | egrep -q "^cert[0-9].?$" ; then
                get_altdistr_mod $1
                return
        fi

        # like M50P or M41
        if echo $1 | egrep -q "^M[0-9][0-9].?$" ; then
                echo $1
                return
        fi
        # it is ok to do nothing here
}

get_type_by_current_branch()
{
        local BRANCH=$(get_current_branch)
        get_type_by_git_branch_name $BRANCH
}

# set BYNARYREPO var by MENV in arg (M70)
set_binaryrepo()
{
	if [ -n "$BINARYREPONAME" ] ; then
		BINARYREPO="$BINARYREPONAME"
		MENV="$(get_altdistr_mod $BINARYREPO)"
		# fill with updated $MENV
		detect_target_env
		return
	else
		# parse MENV
		detect_target_env
		BINARYREPO=$(get_altdistr_version $MENV)
	fi

	# override by the function arg
	test -z "$1" && return
	BINARYREPO="`get_altdistr_version $1`"

	return 0
}

# M60P -> p6
get_altdistr_version()
{
	echo "$1" | sed -e "s|M\([5-9]\)0C|c\1|g" -e "s|M\([5-9]\)0P|p\1|g" -e "s|M\([5-9]\)0T|t\1|g" -e "s|SS|sisyphus|g" -e "s|DD|daedalus|g" -e "s|Sisyphus|sisyphus|g"
}

# p6 -> M60P
get_altdistr_mod()
{
	echo "$1" | sed -e "s|Sisyphus|SS|gi" -e "s|p\([5-9]\)|M\10P|g" -e "s|c\([6-9]\)|M\10C|g" -e "s|t\([6-9]\)|M\10T|g"
}

# TODO: include in sisyphus_check
# Проверяем, соответствует ли релиз пакетов указанному в MENV
pkg_release_check()
{
	assert_var MENV
	# FIXME: more correct way
	[ -n "$KORINFSKIPRELEASECHECK" ] && return 0
	local STREL=$(get_default_txtrelease)
	# support alt in any case
	local STRELDEF=alt
	# can be set from korinf config
	[ -z "$KORINFTARGETRELEASE" ] || STREL=$KORINFTARGETRELEASE
# FIXME! broken for release more than 9
	if [ "$MENV" = "SS" ] || [ "$MENV" = "DD" ] ; then
		for i in $@ ; do
			if rhas "$i" "($STREL|$STRELDEF)[0-9]+\.M[0-9][0-9]\.[0-9]+" ; then
				# Значит не тот релиз
				fatal "Incorrect release in $i package: was prepared for Sisyphus. Check also for KORINFSKIPRELEASECHECK"
			fi
		done
		return
	fi
	for i in $@ ; do
		if ! rhas "$i" "($STREL|$STRELDEF)[0-9]+\.$MENV\.[0-9]+" ; then
			# Значит не тот релиз
			fatal "Incorrect release in $i package: was prepared for $MENV (wait for $STREL[0-9].$MENV)"
		fi
	done
}

# TODO: remove for all, use $ rpmreqs instead
# copied from aptU
get_rpmpkg_requires()
{
	assert_var ETERBUILDBIN
	$ETERBUILDBIN/rpmreqs $@
}

