#!/bin/bash

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

##########################################################
# Utility for sudoit to enter/save/read the sudo password.
# To be used with $SUDO_ASKPASS and sudo --askpass option.
##########################################################

readonly confdir="$HOME/.config/sudoit";
readonly confile="$confdir/secrkey";
declare -i opt_nogui=0;

readonly hostkey="$(cat /etc/machine-id)";
readonly passkey="$confile-$hostkey";

function fatal(){
 1>&2 echo -ne "\n$2\n\n";
 exit $1;
};

function check_confdir(){
 if [[ -d $confdir ]]; then return 0; fi;
 mkdir -p $confdir;
};

function encode_secrkey(){
 ccrypt --encrypt --key "$passkey" | base64;
};

function decode_secrkey(){
 base64 --decode --ignore-garbage | ccrypt --decrypt --key "$passkey";
};

function menu_secrkey(){
 if [[ "${LANG:0:2}" = "ru" ]]; then
  local title="Задание ПАРОЛЯ для sudo …";
 else
  local title="Assign PASSWORD for sudo …";
 fi;
 if zenity --timeout 300 --modal --password --title "$title"; then
  return 0;
 else
  fatal 1 "Error: empty password for sudoit.";
 fi;
};

function save_secrkey(){
 check_confdir;
 if [[ -z "$1" ]]; then return 1; fi;
 echo "$1" | encode_secrkey > $confile;
};

function menu_save_secrkey(){
 local pwd="$(menu_secrkey 2>/dev/null)";
 if [[ -z "$pwd" ]]; then
  fatal 1 "Error: empty password for sudoit.";
  return;
 fi;
 save_secrkey "$pwd";
 echo "$pwd";
};

function read_secrkey(){
 if [[ -r $confile ]]; then
  cat $confile | decode_secrkey;
  return;
 fi;
 if [[ $opt_nogui -ne 0 ]] then
  fatal 1 "Error: no password saved for sudoit. Use --password option.";
  return;
 fi;
 menu_save_secrkey;
};

function obliviate_secrkey(){
 1>&2 rm -fv $confile;
};

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

function main(){
 if [[ "x$SUDOIT_NOGUI" = "x1" ]]; then
  let opt_nogui=1;
 fi;
 case $1 in
  -nogui|--nogui)       let opt_nogui=1; ;;
  -reset|--reset)       menu_save_secrkey > /dev/null; shift; ;;
  -password|--password) menu_save_secrkey > /dev/null; shift; ;;
  -oblivion|--oblivion) obliviate_secrkey > /dev/null; return; ;;
  *) ;;
 esac;
 read_secrkey;
};

main "$@";

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