#!/usr/bin/sh -e
#
# This setup script will install an OS environment by default into
# /usr/share/qm/rootfs and create a Podman quadlet containerized environment
# running systemd as PID1 inside.
#
if [ "$EUID" -ne 0 ];then
    echo "Please run this script as root"
    exit 1
fi

qmContainerIDs=1000000000:1500000000
containerIDs=2500000000:1500000000
replaceIDs() {
    touch $1
    grep -q "^$2:" $1 || echo $2:$3 >> $1
}

INSTALLDIR="$1"
[ ! -z "${INSTALLDIR}" ] || INSTALLDIR=/usr/share/qm

ROOTFS="$2"
[ ! -z "${ROOTFS}" ] || ROOTFS=/usr/lib/qm/rootfs

systemctl stop qm.service 2>/dev/null || true

hirteSetup() {
    rootfs=$1
    if test ! -f ${rootfs}/etc/hirte/agent.conf; then
	if test -f /etc/hirte/agent.conf; then
	    sed -e 's,^NodeName=,NodeName=qm.,g' /etc/hirte/agent.conf >  ${rootfs}/etc/hirte/agent.conf
	fi
    fi
    hostname=$(hostname)
    if test -f ${rootfs}/etc/hirte/agent.conf; then
	sed -e "s,^NodeName=qm.$,NodeName=qm.${hostname},g" \
	    -e "s,^NodeName=$,NodeName=qm.${hostname},g" \
	    -i ${rootfs}/etc/hirte/agent.conf
    else
	cat > ${rootfs}/etc/hirte/agent.conf <<EOF
[hirte-agent]
NodeName=qm.${hostname}
EOF
    fi
    unshare --mount-proc -R /usr/lib/qm/rootfs -m systemctl enable hirte-agent.service
}

install() {
    rootfs=$1
    . /etc/os-release
    mkdir -Z -p ${rootfs}
    dnf -y install --releasever=${VERSION_ID} --installroot ${rootfs} selinux-policy-targeted podman systemd hirte-agent --nogpgcheck
    dnf -y update --installroot ${rootfs} --nogpgcheck
    rm -rf ${rootfs}/etc/selinux/targeted/contexts/files/file_contexts/*
    cp ${INSTALLDIR}/containers.conf ${rootfs}/etc/containers/
    cp ${INSTALLDIR}/contexts ${rootfs}/usr/share/containers/selinux/
    cp ${INSTALLDIR}/file_contexts ${rootfs}/etc/selinux/targeted/contexts/files/file_contexts
    replaceIDs ${rootfs}/etc/subuid containers ${qmContainerIDs}
    replaceIDs ${rootfs}/etc/subgid containers ${qmContainerIDs}
    hirteSetup ${rootfs}
    restorecon -R ${rootfs}
}

install ${ROOTFS}
replaceIDs /etc/subuid qmcontainers ${qmContainerIDs}
replaceIDs /etc/subgid qmcontainers ${qmContainerIDs}
replaceIDs /etc/subuid containers   ${containerIDs}
replaceIDs /etc/subgid containers   ${containerIDs}

systemctl daemon-reload
systemctl start qm.service
