#!/bin/bash
# Open a file with the default application as user
# Usually run from root running applications
# Usage: open-as-user PATH_TO_FILE [USER]
# If [USER] is omitted, the user's login name is used

FLE=$1
USR=$2
if [ ! -e "$FLE" ]; then
    echo "Path $FLE does not exist"
    echo 'Pass the file name: open-as-user PATH_TO_FILE USER_NAME'
    exit 1
fi
if [ -z "$USR" ]; then
    USR=$(logname)
fi

if [ -z "$USR" ]; then
    echo 'Could not retrieve current user name'
    echo 'Pass the user name: open-as-user PATH_TO_FILE USER_NAME'
    exit 2
fi

sudo -H -u $USR xdg-open "$FLE"

exit 0
