#! /bin/sh

# TODO: Detect su-mode or sudo-mode and act accordingly

debug() {
  # Uncomment to debug
  #echo "[DEBUG] $@"
  return
}

debug "CMDLINE ($# ARGS): $0 $@"

# Does the command line contain "--user" ?
if echo " $*" | grep -E -e " (-u|--user)" > /dev/null ; then
  debug "-u or --user detected, parsing"
  # Is "--user" passed to gksu or to the binary called by it ?
  for GKSU_OPTION in "$@" ; do
    # Skip arguments to gksu options
    if [ "$NEXT_OPTION_IS_ARG" = "yes" ] ; then
      debug "$GKSU_OPTION related to previous option, skipping to next"
      NEXT_OPTION_IS_ARG="no"
      continue
    fi
    case $GKSU_OPTION in
      # Skip gksu options with an argument
      -D|-m|--description|--desktop|--message)
        debug "$GKSU_OPTION belongs to gksu, skipping to next"
        NEXT_OPTION_IS_ARG="yes"
        continue ;;
      # Skip gksu options without argument
      -D*|-m*|--|-d|-g|-P|-k|-l|-p|-w|-S|--debug|--disable-grab|--prompt|--preserve-env|--login|--print-pass|--su-mode|--sudo-mode)
        debug "$GKSU_OPTION belongs to gksu, skipping to next"
        continue ;;
      # gksu user option, run the with all arguments as-is and exit
      -u*|--user)
        debug "$GKSU_OPTION belongs to gksu, running command as-is..."
        "/usr/bin/gksu.real" "$@"
        exit $? ;;
      # The command to be run by gksu has been reached, we exit the loop
      *)
        debug "-u or --user doesn't belong to gksu, running command through pkexec..."
        break ;;
    esac
  done
else
  debug "--user not detected"
fi

# If we reach this point, run gksu with all arguments through pkexec
debug "Running: pkexec /usr/bin/gksu.real $@"
pkexec "/usr/bin/gksu.real" "$@"
exit $?
