#!/bin/sh
##
#  Korinf project
#
#  Main korinf script for build packages
#
#  Copyright (c) Etersoft <http://etersoft.ru> 2005-2009, 2013
#  Copyright (c) Vitaly Lipatov <lav@etersoft.ru> 2009, 2013
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Affero General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.

#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Affero General Public License for more details.

#  You should have received a copy of the GNU Affero General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

# Example in the three lines:
#  kormod korinf
#  export REBUILDLIST=Fedora/10
#  build_package your-package-name

kormod message log mainbuild mount

exit_handler()
{
    local rc=$?
    trap - EXIT
    warning "Interrupted, exiting..."
    end_umount
    exit $rc
}

# build binary packages according to REBUILDLIST
# arg: package_name
build_package()
{
	# FIXME: for compatibility
	set_log_dir

	echo | write_report

	local BUILDNAME
	test -n "$1" && BUILDNAME=$1 || fatal "Missed build_rpm param"

	# disable changelog editing
	export EDITOR=

	# used in external get_distro_list
	export SKIPBUILDLIST

	MAINFILESLIST=$MAINFILES
	EXTRAFILESLIST=$EXTRAFILES

	if [ -z "$QUIET" ] ; then
		#echo "Build $BUILDNAME package"
		echo "Source dir: $SOURCEPATH"
		echo "Target dir: $TARGETPATH"
	fi

	if [ -z "$SOURCEPATH" ] || [ -z "$TARGETPATH" ] ; then
		fatal "Source or target path is not set"
	fi

	# HACK: Url for remote building
	SOURCEURL=$(echo $SOURCEPATH | sed -e "s|/var/ftp/|ftp://server/|g")
	readonly SOURCEURL

	TARGETBUILDNAME=$BUILDNAME
	# FIXME HACK: For systems with portage change wine package name
	[ "$BUILDNAME" = "wine" ] && TARGETBUILDNAME="wine-etersoft-public"
	readonly TARGETBUILDNAME

	# IMPROVE: get src.rpm from some private dir
	BUILDSRPM=$(get_src_package "$SOURCEPATH" $BUILDNAME || fatal "Can't find package for $BUILDNAME")
	readonly BUILDSRPM

	PACKAGEVERSION=$(rpm -qp "$BUILDSRPM" --queryformat="%{VERSION}")
	[ -n "$PACKAGEVERSION" ] || fatal "Can't get version from $BUILDSRPM package"
	readonly PACKAGEVERSION

	PACKAGERELEASE=$(rpm -qp "$BUILDSRPM" --queryformat="%{RELEASE}" | sed -e "s|^alt|eter|g")
	[ -n "$PACKAGERELEASE" ] || fatal "Can't get release from $BUILDSRPM package"
	readonly PACKAGERELEASE

	if [ -n "$SRPMGPGCHECKING" ] ; then
		# always failed if gpg is missed
		rpmsign --checksig $BUILDSRPM || fatal "GPG check failed"
	fi

	# Assure we have no too open perms on private key
	if [ -w "$PRIVATESSHKEY" ] ; then
		chmod 600 "$PRIVATESSHKEY" || fatal "SSH key permissions problem"
	fi

	# disable gear using due pre hasher repacking problem
	export IGNOREGEAR=1

	trap exit_handler EXIT HUP INT QUIT PIPE TERM

	if [ -n "$CHECKPACKAGE" ] ; then
		kormod check_built
		check_built_package "$BUILDNAME"
	elif [ -n "$CHECKREQUIRES" ] ; then
		kormod check_reqs
		check_package_requires "$BUILDNAME"
	else
		mainbuild
	fi

	local rc=$?
	# disable trap before exit
	trap - EXIT
	return $rc
}


print_build_project_options()
{
	echo "	-b - buildstrap (build if needed, install package(s) after build)"
	echo "	-B - force buildstrap (even if package is up-to-date)"
	echo "	-q - enable quiet mode"
	echo "	-c - print build status list"
	echo "	-f - force rebuild only failed package(s)"
	echo "	-F - force rebuild all packages (even if package is up-to-date)"
	echo "	-i - install packages required for package build"
	echo "	-I - force install packages required for package build"
	echo "	-r - check install requires"
	echo "	-R - check install requires with print full info"
}

handle_arg()
{
	case "$1" in
	-q)
		QUIET=1
		;;
	-c)
		CHECKPACKAGE=1
		echo "Run checking package status"
		;;
	-b)
		BOOTSTRAP=1
		REBUILDPACKAGE=1
		echo "Run with install built package after done"
		;;
	-B)
		BOOTSTRAP=1
		FORCEREBUILDPACKAGE=1
		echo "Run with install built package after force build done"
		;;
	-f)
		echo "Run with force to rebuild package"
		REBUILDPACKAGE=1
		;;
	-F)
		echo "Run with force to rebuild all packages"
		REBUILDPACKAGE=1
		FORCEREBUILDPACKAGE=1
		;;
	-i)
		echo "Run install required package procedure"
		INSTALLREQUIREDPACKAGE=1
		;;
	-I)
		echo "Force install required package procedure"
		INSTALLREQUIREDPACKAGE=1
		FORCEREBUILDPACKAGE=1
		;;
	-r|-R)
		CHECKREQUIRES="$1"
		echo "Run check package requirements status"
		;;
	-*)
		fatal "Unknown option: $1"
		;;
	*)
		return 1
		;;
	esac
}

handle_optional_args()
{
	local ARG2="$2"
	if [ -n "$1" ] ; then
		REBUILDLIST="$1"
	fi

	if [ -n "$ARG2" ] ; then
		# FIXME: if last part already exists? (ran with /var/ftp/.../Wine-vanilla/1.7.4)
		SP="$SP/$ARG2"
	else
		test -d "$SP/last" && SP="$SP/last"
	fi
}

# build_project /var/ftp/pub/Etersoft/WINE@Etersoft wine-etersoft WINE -f 2.1

# args:
# 1. SP - path to project dir (where versions)
# 2. BUILDNAME - package name
# 3. TP - [target subdir]
# 4. Distro/Version (build list, target_system)
# optional:
# 5. [other project version]
# 6. and more: options
# will set many external vars: CHECKPACKAGE, REBUILDPACKAGE, BOOTSTRAP, FORCEREBUILDPACKAGE, REBUILDPACKAGE, INSTALLREQUIREDPACKAGE, CHECKREQUIRES
build_project()
{
	local SP=$1
	local BUILDNAME=$2
	local TP=$3
	shift 3

	local i

	# 4 arg: possible it is options
	if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
		fatal "We do not handle help here"
	fi

	local GP=
	for i in "$@" ; do
		handle_arg "$i" || GP="$GP $i"
	done

	handle_optional_args $GP

	if [ -z "$QUIET" ] ; then
		export VERBOSE=1
	fi

	TARGETPATH=$(readlink -f "$SP")
	
	if [ -n "$ADEBUG" ]
	then
	    debug_print_var TARGETPATH SP
	    debug_print_backtrace
	fi

	# check rpmpub for the same sources check
	# set SOURCEPATH, add sources if not yet
	if rhas "$TARGETPATH" "/sources" ; then
		SOURCEPATH=$TARGETPATH
		# drop sources from TARGETPATH if was set
		TARGETPATH=$(dirname $TARGETPATH)
	else
		SOURCEPATH=$TARGETPATH/sources
	fi
	readonly SOURCEPATH

	[ -n "$TARGETPATH" ] || fatal "Cannot find target path $SP, check it"

	readonly PROJECTVERSION=$(basename $TARGETPATH)
	[ -n "$ADEBUG" ] && echo "PROJECTVERSION=$PROJECTVERSION"

	# set according to base TARGETPATH, so set before TP
	set_rebuildlist

	[ -z "$TP" ] || TARGETPATH=$TARGETPATH/$TP
	readonly TARGETPATH

	build_package $BUILDNAME
}
