#!/bin/sh

PROJECT_NAME=belenios

set -e

DIR="$1"
shift

NAME="${DIR##*/}"

# We drop all systemd-nspawn's default capabilities, except:
# - CAP_KILL (for daemon management)
# - CAP_SETGID, CAP_SETUID (for running unprivileged processes)
# - CAP_SYS_ADMIN (needed for `mount` in boot scripts)
# - CAP_SYS_BOOT (needed to shutdown the container)
# - CAP_SETPCAP, CAP_SYS_CHROOT (needed in boot scripts)
# - CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_DAC_READ_SEARCH, CAP_FOWNER (needed by logrotate)

CAPFLAGS=--drop-capability=CAP_AUDIT_CONTROL,CAP_AUDIT_WRITE,CAP_FSETID,CAP_IPC_OWNER,CAP_LEASE,CAP_LINUX_IMMUTABLE,CAP_MKNOD,CAP_NET_BIND_SERVICE,CAP_NET_BROADCAST,CAP_NET_RAW,CAP_SETFCAP,CAP_SYS_NICE,CAP_SYS_PTRACE,CAP_SYS_RESOURCE,CAP_SYS_TTY_CONFIG

if [ -d "$DIR/$PROJECT_NAME/var" ]; then
    exec systemd-nspawn --image=$DIR/rootfs.squashfs --overlay=+/var::/var --bind-ro=$DIR/$PROJECT_NAME/etc:/etc/$PROJECT_NAME --bind=$DIR/$PROJECT_NAME/var:/var/$PROJECT_NAME --machine=$PROJECT_NAME-$NAME $CAPFLAGS "$@"
else
    exec systemd-nspawn --image=$DIR/rootfs.squashfs --overlay=+/var::/var --bind=$DIR/$PROJECT_NAME:/var/$PROJECT_NAME --machine=$PROJECT_NAME-$NAME $CAPFLAGS "$@"
fi
