#!/bin/bash
# Copyright (C) 2024 Koozali Organisation
# SPDX-License-Identifier: Apache-2.0

set -e
DEBUG=
SILENT="-s"
QUIET="-q"
for param in $1 $2 ; do
  if [ $param ] ; then
    case $param in
	    debug )
		    DEBUG="debug" ;;
    esac
  else
	  break
  fi
done

if [ $DEBUG ] ; then
    set -xe
    SILENT=
    QUIET="-v"
fi

# load required parameters
SCRIPT_DIR="$(dirname "$(realpath "$0")")"
if [ ! -f "$SCRIPT_DIR"/koji-parameters.sh ] ; then
    echo "$SCRIPT_DIR/koji-parameters.sh NOT found - aborting"
    exit 1
fi
source "$SCRIPT_DIR"/koji-parameters.sh
KOJI_BUILD_FQDN="$(hostname -f)"

# create the compose directory and change ownership
mkdir /mnt/koji/compose
chown kojiadmin:kojiadmin /mnt/koji/compose

# setup runroot on the hub
# Install the koji builder components from epel
if [[ -z $(dnf list installed | grep koji-hub-plugins) ]] ; then
	dnf install -y koji-hub-plugins $QUIET
fi

# configure runroot to run on the hub
# add Plugins = runroot_hub to /etc/koji-hub/hub.conf

# deploy runroot to the builders
# use builders from api call


## On the builders
for FQDN in ${KOJI_BUILD_FQDNS} ; do
    # copy across the global koji parameters
    ssh $QUIET root@$KOJI_BUILD_FQDN mkdir -p $SCRIPT_DIR
    scp $QUIET $SCRIPT_DIR/koji-parameters.sh root@$KOJI_BUILD_FQDN:$SCRIPT_DIR/koji-parameters.sh
    # pull down the required scripts
    ssh $QUIET root@$KOJI_BUILD_FQDN "curl $SILENT $SCRIPT_GIT/koji-deploy-pungi-builder.sh > $SCRIPT_DIR/koji-deploy-pungi-builder.sh"
    # make them executeable
    ssh $QUIET root@$KOJI_BUILD_FQDN "chmod o+x $SCRIPT_DIR/*"
    
    # setup runroot on the koji builder
    ssh $QUIET root@$KOJI_BUILD_FQDN $SCRIPT_DIR/koji-deploy-pungi-builder.sh $DEBUG
done