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

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

    systemctl --user stop $name > /dev/null 2>&1
    podman container rm $name > /dev/null 2>&1
    id=$(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=registry" \
        --publish 127.0.0.1:$PORT:8080 \
        --user 0 \
        --volume ~/museum/$bn:/museum \
        --volume ~/log/fossil:/log \
        $IMAGE \
            --scgi \
            --nojail \
            --jsmode bundled \
            --baseurl $SITE/$bn \
            --errorlog /log/$bn.log \
            /museum/repo.fossil)
    sfile=~/.local/share/systemd/user/$name.service
    podman generate systemd --new --name $name > $sfile

    if [ -z "$FIRST" ]
    then
        ov=$(fossil version)
        podman cp $name:/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))
}

podman image pull $IMAGE

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

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