#!/bin/bash
IMAGE=docker.io/tangentsoft/fossil
SITE=https://example.com
PORT=12345

function start_one() {
    bn=$1
    ln="$2"
    name=fossil-$bn

    sudo systemctl stop $name      > /dev/null 2>&1
    sudo podman container rm $name > /dev/null 2>&1
    id=$(sudo podman create \
        --name $name \
        --cap-drop AUDIT_WRITE \
        --cap-drop CHOWN \
        --cap-drop FSETID \
        --cap-drop KILL \
        --cap-drop NET_BIND_SERVICE \
        --cap-drop NET_RAW \
        --cap-drop SETFCAP \
        --cap-drop SETPCAP \
        --label "io.containers.autoupdate=image" \
        --publish 127.0.0.1:$PORT:8080 \
        --volume ~/museum/$bn:/jail/museum \
        --volume ~/log/fossil:/jail/log \
        $IMAGE \
        bin/fossil server \
            --scgi \
            --chroot /jail \
            --jsmode bundled \
            --baseurl $SITE/$bn \
            --errorlog /log/$bn.log \
            museum/repo.fossil)
    sudo podman generate systemd --new --name $name |
        sudo dd status=none of=/etc/systemd/system/$name.service

    if [ -z "$FIRST" ]
    then
        ov=$(fossil version)
        sudo podman cp $name:/jail/bin/fossil $(type -p fossil)
        nv=$(fossil version)
        echo -e "Updated Fossil:\n  From: $ov\n    To: $nv"
        FIRST=0
    fi

    echo Created $ln Fossil container, port $PORT, ID ${id:0:8}.

    NAMES="$NAMES $name"
    PORT=$(($PORT + 1))
}

sudo podman image pull $IMAGE

start_one first  "First Project"
start_one second "Second Project"
start_one third  "Third Project"

set -x
sudo systemctl daemon-reload
sudo systemctl enable  $NAMES
sudo systemctl restart $NAMES
