#! /bin/bash

set -ex

skip="cockpit-doc-"

do_build=
do_install=
mock_opts=""
args=$(getopt -o "vqs:" -l "verbose,quick,skip:,build,install,rhel" -- "$@")
eval set -- "$args"
while [ $# -gt 0 ]; do
	case $1 in
	    -v|--verbose)
                mock_opts="$mock_opts --verbose"
		;;
	    -q|--quick)
                mock_opts="$mock_opts --nocheck --define='selinux 0'"
		;;
            -s|--skip)
                skip="$skip
$2"
                shift
                ;;
            --build)
                do_build=t
                ;;
            --install)
                do_install=t
                ;;
            --rhel)
                # For RHEL we actually build in EPEL, which is based
                # on CentOS.  On CentOS, the spec file has both
                # %centos and %rhel defined, but it gives precedence
                # to %centos, as it must.  To make it produce the RHEL
                # packages, we explicitly undefine %centos here.
                mock_opts="$mock_opts --define='centos 0'"
                ;;
	    --)
		shift
		break
		;;
	esac
	shift
done
tar=$1

# Build

if [ -n "$do_build" ]; then
    rm -rf build-results
    srpm=$(/var/lib/testvm/make-srpm "$tar")
    LC_ALL=C.UTF-8 su builder -c "/usr/bin/mock --offline --no-clean --resultdir build-results $mock_opts --rebuild $srpm"
fi

# Install

if [ -n "$do_install" ]; then
    packages=$(find build-results -name "*.rpm" -not -name "*.src.rpm" | grep -vF "$skip")
    rpm -U --force $packages

    if type firewall-cmd > /dev/null 2> /dev/null; then
        firewall-cmd --add-service=cockpit --permanent
    fi

    rm -rf /var/log/journal/*
    rm -rf /var/lib/NetworkManager/dhclient-*.lease
fi
