#!/bin/sh -eux

BACKEND="${BACKEND:-lorax-composer}"
SRPM="$1"

# always remove older versions of these RPMs if they exist
# to ensure newly built packages have been installed
yum -y remove lorax $BACKEND composer-cli

if ! rpm -q beakerlib; then
    if [ $(. /etc/os-release && echo $ID) = "rhel" ]; then
        (cd /etc/yum.repos.d; curl -O -L http://download.devel.redhat.com/beakerrepos/beaker-client-RedHatEnterpriseLinux.repo)
        # disable sslverify b/c yum will fail to sync metadata otherwise
        sed -i "s/\(gpgcheck=0\)/\1\nsslverify=0/" /etc/yum.repos.d/beaker-client-RedHatEnterpriseLinux.repo
        # do not remove the repo file. We now have tests which use beakerlib
        # inside their blueprints so this needs to stay on the VM
    fi

    yum install -y beakerlib
fi

if ! rpm -q python36; then
    yum -y install python36
fi

if ! rpm -q python3-pytoml; then
    yum -y install python3-pytoml
fi

if ! rpm -q git; then
    yum install -y git
fi

if ! rpm -q qemu-kvm; then
    yum install -y qemu-kvm
fi

# Grow root partition on LVM test images to make room for built images
PVS=$(pvs --noheadings -opv_name)
if [ -n "$PVS" ]; then
    echo ", +" | sfdisk -N 2 -f /dev/vda
    partprobe
    echo "$PVS" | xargs pvresize
    rootlv=$(findmnt --noheadings -oSOURCE /)
    lvresize $rootlv -l+100%FREE -r
fi

rm -rf build-results
su builder -c "/usr/bin/mock --no-clean --resultdir build-results --rebuild $SRPM"

packages=$(find build-results -name '*.rpm' -not -name '*.src.rpm')
if [ "$BACKEND" == "osbuild-composer" ]; then
    packages=$(find build-results -name '*.rpm' -not -name '*.src.rpm' -not -name '*lorax-composer*')
fi
yum install -y $packages $BACKEND

systemctl enable $BACKEND.socket

if [ -f /usr/bin/docker ]; then
    yum remove -y $(rpm -qf /usr/bin/docker)
fi

if ! rpm -q podman-docker; then
    yum install -y podman-docker
fi
