#!/usr/bin/bash
set -eu

exit_script() {
    echo "unmounting media - terminated by trap!" >> "/tmp/${SUDO_UID}-exit-mount.log"
    findmnt "/lmn/media/${SUDO_USER}/share" && umount "/lmn/media/${SUDO_USER}/share"
    findmnt "/srv/samba/schools/default-school" && umount "/srv/samba/schools/default-school"
    trap - SIGHUP SIGINT SIGTERM # clear the trap
    kill -- -$$ # Sends SIGTERM to child/sub processes
}

findmnt /srv/samba/schools/default-school > /dev/null && exit 0

umask 0002
mkdir -p /srv/samba/schools/default-school
chmod 777  /srv/samba/schools/default-school
mkdir -p "/lmn/media/${SUDO_USER}/share"

mount -t cifs //server/default-school/ /srv/samba/schools/default-school \
      -o "sec=krb5i,cruid=${SUDO_UID},user=${SUDO_USER},uid=${SUDO_UID},gid=1010,file_mode=0770,dir_mode=0770,mfsymlinks,nobrl,actimeo=600,cache=loose,echo_interval=10"
mount --bind /srv/samba/schools/default-school/share "/lmn/media/${SUDO_USER}/share"

echo "Einbindung erfolgreich!"
echo "Dieses Fenster bitte nicht schließen!"
trap exit_script SIGHUP SIGINT SIGTERM
sleep infinity
