#!/bin/bash
#
# mount wrapper for pam_mount
# frank@linuxmuster.net
#
# 15.04.2012
# GPL v2
#

# default value for PROFILE_USER
PROFILE_USER="linuxadmin"
# if the package linuxmuster-client-profile is installed,
# configuration is stored in /etc/linuxmuster-client/profile.conf
if [ -f /etc/linuxmuster-client/profile/profile.conf ]; then
.  /etc/linuxmuster-client/profile/profile.conf
fi

# args
SERVER=$1
VOLUME=$2
MNTPT=$3
USER=$4
OPTIONS="$5"


# functions
log_msg() {
    logger -t linuxmuster-pam-mount "$1"
}

run_hook() {
    local script="$1"
    local exit_status
    shift   # discard the first argument, then the rest are the script's

    if [ -f $script ]; then
        . $script "$@"
    fi

    if [ -n "$exit_status" ] && [ "$exit_status" -ne 0 ]; then
        logger -p daemon.err "$script returned non-zero exit status $exit_status"
        save_exit_status=$exit_status
    fi

    return $exit_status
}

run_hookdir() {
    local dir="$1"
    local exit_status
    shift   # See run_hook

    if [ -d "$dir" ]; then
        for script in $(run-parts --list $dir); do
            run_hook $script "$@" || true
            exit_status=$?
        done
    fi

    return $exit_status
}

# Log invocation and parameters
log_msg "Invoked with: SERVER $SERVER, VOLUME $VOLUME, MNTPT $MNTPT, USER $USER OPTIONS $OPTIONS"

# mounting part starts here

# check if params are all set
[ -z "$SERVER" ] && exit 1
[ -z "$VOLUME" ] && exit 1
[ -z "$MNTPT" ] && exit 1
[ -z "$USER" ] && exit 1
# at least user=USERNAME has to beg iven as an option
[ -z "$OPTIONS" ] && exit 1

# no mounting for lightdm session
if [ "$USER" == "lightdm" ]; then exit 0; fi
# no mounting, no hooks for PROFILE_USER
if [ "$USER" == "$PROFILE_USER" ]; then exit 0; fi
# no pammount for local users
grep -q ^${USER}: /etc/passwd && exit 0

# PRE MOUNT HOOK
log_msg "pre-mount sequence: run_hookdir /etc/linuxmuster-client/pre-mount.d $USER $VOLUME $MNTPT $SERVER $OPTIONS"
run_hookdir /etc/linuxmuster-client/pre-mount.d $USER $VOLUME $MNTPT $SERVER $OPTIONS

# mount the given share
log_msg "Executing mount: mount -t cifs //${SERVER}/${VOLUME} $MNTPT -o \"$OPTIONS\""

mount -t cifs //${SERVER}/${VOLUME} $MNTPT -o "$OPTIONS" || exit 1

# POST MOUNT HOOK
log_msg "post-mount sequence: run_hookdir /etc/linuxmuster-client/post-mount.d $USER $VOLUME $MNTPT $SERVER $OPTIONS"
run_hookdir /etc/linuxmuster-client/post-mount.d $USER $VOLUME $MNTPT $SERVER $OPTIONS
