#!/bin/bash

##########################################################
# Copyright (c) 2001-2026 Alexey Kuryakin daqgroup@mail.ru
##########################################################

##########################################################
# Utility to call sudo with required options.
##########################################################

################################
# Current script identification.
################################
readonly scriptfile="${BASH_SOURCE[0]}";
readonly scriptname="$(basename $scriptfile)";
readonly scriptbase="$(basename $scriptfile .sh)";
readonly scriptFILE="$(realpath $scriptfile)";
readonly scriptHOME="$(dirname  $scriptFILE)";

readonly askpass="$scriptHOME/$scriptbase-askpass.sh";

function logg(){
 if [[ -n $CRW_DAQ_VAR_TMP_DIR ]] && [[ -d $CRW_DAQ_VAR_TMP_DIR ]]; then
  local logfile="$CRW_DAQ_VAR_TMP_DIR/sudoit.log"; local logtime="$(date +%Y.%m.%d-%H:%M:%S.%N)";
  echo "${logtime:0:23} => INFO/NOTIFY: $(hostname)/$CRW_DAQ_SYS_SESSION_HEAD/sudoit - $*" >> $logfile;
 fi;
};

######
# MAIN
######

function main(){
 case $1 in
  -password|--password) $askpass --password > /dev/null; shift; ;;
  -oblivion|--oblivion) $askpass --oblivion > /dev/null; return; ;;
  *) ;;
 esac;
 if [[ -z "$1" ]]; then return; fi;
 export SUDOIT_NOGUI="${SUDOIT_NOGUI:-1}";
 export SUDO_ASKPASS="$askpass";
 # prepare options
 local -a options=();
 options+=("-A");
 # execute sudo with options
 logg sudo "${options[@]}" "$@";
 exec sudo "${options[@]}" "$@";
};

main "$@";

##############
## END OF FILE
##############
