#!/bin/sh -ef

[ -n "$COMFORT_DIR" ] || COMFORT_DIR=/usr/share/comfort
. "$COMFORT_DIR/functions"

# ======================================================================

USAGE='[package-name]'
DESCRIPTION='Build package from git repository in hasher.'

# Parse command line
. "$COMFORT_DIR/getopt"
[ "$#" -le 1 ] || show_usage 'Too many arguments'
determine_package $1

# ======================================================================

# Build package
pushd $GIT_HOME_DIR/$PACKAGE >/dev/null
LOG_FILE=`mktemp -t`

if [ -n "$BUILD_SERVER_HOST" ]; then
	gear --commit pkg.tar
	ssh $BUILD_SERVER_HOST mkdir -p "$BUILD_SERVER_BUILD_DIR"
	scp pkg.tar "$BUILD_SERVER_HOST:$BUILD_SERVER_BUILD_DIR"
	rm -f pkg.tar
	ssh -l $BUILD_SERVER_USER $BUILD_SERVER_HOST hsh --target=$ARCH "$BUILD_SERVER_BUILD_DIR" "$BUILD_SERVER_BUILD_DIR/pkg.tar" | tee $LOG_FILE
	mkdir -p "$BUILD_DIR/repo/$ARCH/RPMS.hasher" "$BUILD_DIR/repo/SRPMS.hasher"
	rsync -rltp "$BUILD_SERVER_HOST:$BUILD_SERVER_BUILD_DIR/repo/$ARCH/RPMS.hasher/" "$BUILD_DIR/repo/$ARCH/RPMS.hasher"
	rsync -rltp "$BUILD_SERVER_HOST:$BUILD_SERVER_BUILD_DIR/repo/SRPMS.hasher/" "$BUILD_DIR/repo/SRPMS.hasher"
else
	gear --commit --hasher -- hsh --target=$ARCH "$BUILD_DIR" | tee $LOG_FILE
fi

popd >/dev/null

# Analyze log file
Verbose "Log file: $LOG_FILE"
if grep -qe '^Wrote: /usr/src/RPM' $LOG_FILE; then
	echo
	echo ========================================================================
	echo Build succeeded! You can try to:
	echo 
	echo * Install binary packages
	sed -ne "/^Wrote: \/usr\/src\/RPM\/RPMS/ s,^.*/,sudo rpm -U $BUILD_DIR/repo/$ARCH/RPMS.hasher/,p" <$LOG_FILE
	echo
	echo * Publish SRPMS in Sisyphus incoming
	sed -ne "/^Wrote: \/usr\/src\/RPM\/SRPMS/ s,^.*/,Sisyphus-publish $BUILD_DIR/repo/SRPMS.hasher/,p" <$LOG_FILE
	echo
	echo ========================================================================
fi
