#!/bin/bash
readonly PATH=/usr/bin:/bin
readonly IFS=$' \t\n'

while getopts :v:l:u:w:d: OPT; do
  case $OPT in
    v|+v)
      declare -ir OLFSVER=$OPTARG
      ;;
    l|+l)
      readonly BACKUP=$OPTARG
      ;;
    u|+u)
      readonly UPPER=$OPTARG
      ;;
    w|+w)
      readonly WORK=$OPTARG
      ;;
    d|+d)
      readonly TMP=$OPTARG
      ;;
  esac
done
shift $(( OPTIND - 1 ))
OPTIND=1

## TODO - pass error codes back to psd so it can break if the mount command fails
case "$1" in
  mountup)
    # write access to upper/workdir is required or do not overlay lowerdirs
    user=$(stat -c %U "$TMP")
    if ! sudo -u "$user" test -w "$BACKUP"; then
      echo "User $user has no write permissions for $BACKUP. Aborting..." >&2
      exit 1
    fi

    user=$(stat -c %U "$UPPER")
    if ! sudo -u "$user" test -w "$BACKUP"; then
      echo "User $user has no write permissions for $BACKUP. Aborting..." >&2
      exit 1
    fi
    if [[ $OLFSVER -eq 23 ]]; then
      mount -o nosuid,nodev -t overlay overlaid -olowerdir="$BACKUP",upperdir="$UPPER",workdir="$WORK" "$TMP"
    elif [[ $OLFSVER -eq 22 ]]; then
      mount -o nosuid,nodev -t overlayfs overlaid -olowerdir="$BACKUP",upperdir="$UPPER" "$TMP"
    fi
    ;;
  mountdown)
    umount -l "$TMP"
    ;;
  *)
    echo "Do not call this script directly; psd will do so for you. Thank you, come again."
    exit 0
    ;;
esac

# vim:set ts=2 sw=2 et:
