#!/bin/sh

# invoke with 
#     su klutshnik -c "./sbox.sh /usr/bin/klutshnikd /etc/klutshnik/config klutshnik.bpf"
#
# notice: wordexp will not work in the jail, since at least musl actually exec /bin/sh to eval a printf
# also important the cfg file must not use spaces around the = signs, otherwise sourcing it will fail
# during sourcing the cfg file there is one error/warning regarding [server] which can be ignored
# seccomp.bpf can be generated by following the steps in seccomp/README.md

libs=$(ldd "$1" | fgrep -v linux-vdso.so | sed 's;.*\s\(/[^ ]*\) (0x[0-9a-f]*)$;\1;' | sort -u)
libdirs=$(echo "$libs" | sed 's;\(/.*/\).*;\1;' | sort -u)
mkdirs=$(echo "$libdirs" | sed 's;\(.*\);--dir \1;')
libinds=$(echo "$libs" | sed 's;\(.*\);--ro-bind \1 \1;')

source "$2" 2>/dev/null

ulimit -s 196600

# clear environment
env -i \
bwrap --unshare-all \
      --share-net \
      --hostname klutshnik-rpi \
      --die-with-parent \
      --ro-bind "$1" /klutshnikd \
      --file 0 /klutshnikd.cfg \
      --bind "$datadir" /data \
      --ro-bind "$ssl_cert" /cert.pem \
      --ro-bind "$ssl_key" /key.pem \
      --ro-bind "$ltsigkey" /ltsig.key \
      --ro-bind "$noisekey" /noise.key \
      --ro-bind "$authorized_keys" /authorized_keys \
      $mkdirs $libinds \
      --dev /dev \
      --seccomp 11 11<$3 \
      --chdir / \
      /klutshnikd <<EOCFG
[server]
ssl_key="/key.pem"
ssl_cert="/cert.pem"
port=2323
address="${address:-::}"
timeout=${timeout:-3}
datadir="/data"
max_kids=${max_kids:-5}
verbose=${verbose:-false}
record_salt="${record_salt}"
authorized_keys="/authorized_keys"
ltsigkey="/ltsig.key"
noisekey="/noise.key"
EOCFG
