#!/bin/bash
# minimal config version
MIN_VERSION="3.0"

CFG=/etc/notamock.cfg
CFGD=/etc/notamock.d

# special config for project
if [ -f './notamock.cfg' ] ; then 
	CFG=$(realpath ./notamock.cfg)
	CFGD=''
fi

PLATFORM=$(rpm --eval %distro_release)
VARIABLES=''
BUILD_args=''
WATCH_LINES=5
PARALLEL=${PARALLEL:-1}
BUILDER_NAME=${BUILDER_NAME:-$(hostname)}
VERBOSE=yes

HLP(){
echo "$0 - script to start abf builders (builder-c) in notamockd containers"
echo "
Warning! Do not use in host system.

Usage:
	$0 <variables> <parameters>"
echo "Parameters:
	-c | --config        -  specify config file, default is /etc/notamock.cfg
	-h | --help          -  this help
	-t | --token         -  abf token
	-b | --builder_name  -  common prefix for builder IDs (also known as hostname in abf terminology)
	-p | --parallel      -  number of builders
	-w | --watch         -  Monitor processes using the watch command, 
	                        you can specify the number of lines per process, by default $WATCH_LINES.
"
exit
}

NOTAMOCKLIB="/usr/share/notamock/libnotamock"
[ -f './libnotamock' ] && NOTAMOCKLIB=./libnotamock
source "$NOTAMOCKLIB"

echo "==> $(basename $0): find parameters"
sep=''
while [ -n "$1" ] ; do
	case "${1}" in
	"-h" | "--help") HLP ;;
	"-c" | "--config")  shift 
						CFG="$1" 
						CFGD='' ;;
	"-t" | "--token") shift ; TOKEN="$1" ;;
	"-b" | "--builder_name") shift ; BUILDER_NAME="$1" ;;
	"-p" | "--parallel") shift ; PARALLEL="$1" ;;
	"-r" | "--release") shift ; PLATFORM="$1" ;; 
	"--tmux")    TMUX="yes" ;;
	"--watch" )  		WATCH="yes"
						if expr $2 + 1 ; then
							shift
							WATCH_LINES="$1"
						fi >/dev/null 2>&1 ;;
	*)  if echo "$1" |grep -q '=' ; then
			VARIABLES="${VARIABLES}${sep}$(echo $1 |sed 's/ /#/g')"
			sep=' '
		else
			echo_exit "Unknown parameter: $1" ${LINENO}
		fi;;
	esac
shift
done
echo "==> $(basename $0): seting up variables from cmdline"

source "$CFG"
VER=${CFG_VERSION:-0.1}
if [ $(echo -e "$VER\n$MIN_VERSION" |sort -V| tail -n1) != "$VER" ] ; then
	echo "Version of config file is less then minimum required for $0.
$VER < $MIN_VERSION
Please update $CFG from /usr/share/notamock/default.notamock.cfg"
	exit
fi

if [ -d "$CFGD" ] ; then
	for a in $(ls -1 ${CFGD}/. |sort ) ; do
		source ${CFGD}/$a
	done
fi

for a in $VARIABLES; do
	echo "==> $(basename $0):  variable: $a"
	a=$(echo $a |sed 's/#/ /g')
	if echo "$a" |grep -q '[[:alnum:]]*+=.*$' ; then
		eval $(echo $a |sed -e 's/=/=("/' -e 's/$/")/')
	elif echo "$a" |grep -q '[[:alnum:]]*=.*$' ; then
		eval $(echo $a |sed -e 's/=/="/' -e 's/$/"/')
	fi
done

PM_opts="$PM_opts \
$PM_cfg_opt $PM_config \
$PM_addrep_opt $PM_cache"

for str in $(seq 0 $(( ${#ENV[@]} - 1 )) ) ; do
	echo "==> $(basename $0): set env: ${ENV[$str]}"
	eval export ${ENV[$str]}
done

echo "==> $(basename $0): Prepare builder environment"
rm -f /etc/localtime 
ln -s /usr/share/zoneinfo/UTC /etc/localtime
groupadd mock
useradd -m -G mock,wheel -r omv
[ -d /etc/mock ] && chown -R omv:mock /etc/mock
sed -i -e "s/Defaults    requiretty.*/ #Defaults    requiretty/g" /etc/sudoers
echo "%mock ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

echo "==> $(basename $0): Installing builder-c and other necessary packages"
vrun $PM_update $PM_opts
vrun $PM_install $PM_opts $BUILDER_list

echo "==> $(basename $0): Fix builder-c scripts path"
sed -i 's:git.*:path = "'"${BUILDER_scripts}"'":' /etc/builder-c/builder.conf
sed -i '/branch/d' /etc/builder-c/builder.conf

echo "==> $(basename $0): Fix sudo suid bit that have been lost in the docker image"
chmod 4111 /usr/bin/sudo

[ -f /ENV.lst ] && vrun source /ENV.lst
vrun export BUILD_TOKEN="${BUILD_TOKEN:-$TOKEN}"
[ $(echo "$BUILD_TOKEN" |wc -c) -lt 10 ] && echo_exit "Need abf token" ${LINENO}
vrun export BUILD_ARCH=$(uname -m)
vrun export BUILD_PLATFORM_TYPE="dnf"
vrun export LOG_LEVEL="${LOG_LEVEL:-"INFO"}"
vrun export BUILD_PLATFORM="${BUILD_PLATFORM:-$BUILDER_platforms}"
if [ "$PARALLEL" -ne 1 ] ; then 
	for a in $(seq -s ' ' $PARALLEL) ; do
		(vrun export BUILDER_ID=${BUILDER_NAME}_$a 
		 vrun export BUILD_WORKDIR="/home/omv/$BUILDER_ID"
		mkdir -p "$BUILD_WORKDIR"
		chown omv:omv -R "$BUILD_WORKDIR"
		if [ "$WATCH" ] ; then 
			builder > /tmp/${BUILDER_ID} 2>&1
		else
			builder 2>&1
		fi ) &
		echo "==> $(basename r$0): Builder ${BUILDER_NAME}_$a - started"
		sleep 1
	done

	if [ "$WATCH" ] ; then
		wait_cmdline="$(for a in $(seq $PARALLEL) ; do
		echo "echo ${BUILDER_NAME}_$a:"
		echo "find /home/omv/${BUILDER_NAME}_$a/ -maxdepth  2 -name '*.spec'"
		echo "tail -n${WATCH_LINES} /tmp/${BUILDER_NAME}_$a 2>&1"
		echo 'echo'
		done)"
		if [ "$TMUX" ] ; then
			tmux new-session -d -s "notamocka" -n "watch"
			tmux send-keys "watch -t -n 1 \"$wait_cmdline\"" C-m
			tmux attach-session -t "notamocka"
		else
			watch -t -n 1 "$wait_cmdline"
		fi
	else 
		exec /bin/bash
	fi
else
	vrun export BUILDER_ID="$BUILDER_NAME" 
	vrun export BUILD_WORKDIR="/home/omv/${BUILDER_ID}"
	mkdir -p "$BUILD_WORKDIR"
	chown omv:omv $BUILD_WORKDIR
	if [ "$TMUX" ] ; then
		tmux new-session -d -s "notamocka" -n "builder"
		tmux send-keys "builder" C-m
		tmux attach-session -t "notamocka"
	else
		builder
	fi
fi
