#!/usr/bin/env bash

set -euo pipefail;

LOGFILE="/tmp/usb_automount.log";
USERNAME={{ admin_user | quote }};
PROCNAME="caja";
MANAGER_NAME="caja";

function log() {
    if [ -z "${1:-}" ]; then
        /usr/bin/env ts '[%Y-%m-%d %H:%M:%S]' >> "$LOGFILE";
    else
        echo "$@" | log;
    fi
}

function mkdirU() {
    log "Ensure $2 exists and is owned by $1";
    mkdir -p "$2" 2>&1 | log;
    chown "$1:$1" "$2" 2>&1 | log;
}

function getVal() {
    grep --only-matching --perl-regexp '(?<=\s'"$1"'=")[0-9A-Za-z-]+(?=")' || true;
}

function getMountDir() {
    local info="$(blkid "$2")";
    local label="$(<<<"$info" getVal LABEL)";
    local uuid="$(<<<"$info" getVal UUID)";
    local partuuid="$(<<<"$info" getVal PARTUUID)";
    if [ -n "$label" ]; then
        echo "$1/$label";
    elif [ -n "$uuid" ]; then
        echo "$1/$uuid";
    elif [ -n "$partuuid" ]; then
        echo "$1/$partuuid";
    else
        mktemp -d "$1/usb.XXXXXXXX";
    fi
}

log "Inserted device $DEVNAME";

mountDir="/media/$USERNAME";
mkdirU "$USERNAME" "$mountDir";

log "Get userId and groupId of $USERNAME";
userId=$(id -u "$USERNAME");
groupId=$(id -g "$USERNAME");

log "Get directory to mount $DEVNAME";
mountDir="$(getMountDir "$mountDir" "$DEVNAME")";
mkdirU "$USERNAME" "$mountDir";
log "Mount device $DEVNAME to $mountDir"
if ! mount -o ro,uid=$userId,gid=$groupId "$DEVNAME" "$mountDir" 2>&1 | log; then
    log "Failed to mount $DEVNAME";
    exit 2;
fi

procId="$( (ps --user "$USERNAME" --format pid=,cmd= | grep --only-matching --perl-regexp '(?<!\d)\d+(?=\s'"$PROCNAME)") || echo "")";
if [ -z "$procId" ]; then
    log "Admin user is not logged in => do not open file manager";
    exit 0;
fi

while read -r -d "" record; do
    if [[ $record =~ ^[a-zA-Z_][a-zA-Z0-9_]*= ]]; then
        export "$(printf %q "$record")";
    fi
done < /proc/"$procId"/environ;
log "Try to launch $MANAGER_NAME on DISPLAY=$DISPLAY";
sudo -u "$USERNAME" "$MANAGER_NAME" "$mountDir" &
log "Launched file manager";
