#!/bin/bash
#
# __copy1__
# __copy2__
#
CMD=$(basename $0)
CMDVER="1.2"
CMDSTR="$CMD v$CMDVER (2024-09-02)"

set -e -u


usage()
{
	echo "
usage: $CMD action [file]

action:
  get		echoes the full list of credentials
  crypt		encrypt the password in 'file' (using gpg)
  decrypt	unencrypt the password in 'file'
  edit		perform unecrypt/edit/crypt sequence
  		(uses \$EDITOR env var)

notes:
  - default file is '$file'
  - crypt/decrypt will work directly on file
" >&2
	[ $# != 0 ] && echo -e "\n$@\n" >&2
	exit 127
}

decode_credentials()
{
	local buf=
	local line=
	local decoded=
	local sys=
	local user=
	local pass=


	if grep -q "$magic" "$file"
	then
		echo -e "\nEnter password to decrypt '$file':\n" >&2
		buf=$(sed -e '1,2d' "$file" | gpg --decrypt)
		echo "$buf"
	else
		cat "$file"
	fi
}


crypt_file()
{
	head -1 "$file" | grep -q "^$magic$" && {
		echo -e "\n$CMD error: file '$file' already crypted\n" >&2
		echo -e "  (detected magic string '$magic')\n" >&2
		return 1
	}
	echo -e "\nENTER A PASSWORD TO CRYPT '$file'"
	echo -e "(you can use a new password or the previous one)\n"

	echo "$magic"	>"$file.new"
	echo "$comment"	>>"$file.new"
	gpg --cipher-algo AES256 --symmetric <"$file" >>"$file.new"

	rm -f "$file.old"
	mv "$file" "$file.old"
	mv "$file.new" "$file"
	chmod --reference "$file.old" "$file"
	touch --reference "$file.old" "$file"

	return 0
}


decrypt_file()
{
	local buf=

	grep -q "$magic" "$file" || {
		echo -e "\n$CMD error: file '$file' not crypted\n" >&2
		echo -e "  (missing magic string '$magic')\n" >&2
		return 1
	}
	echo -e "\nENTER THE GPG PASSWORD TO DECRYPT '$file'\n"

	sed -e '1,2d' "$file" | gpg --decrypt >"$file.new"

	rm -f "$file.old"
	mv "$file" "$file.old"
	mv "$file.new" "$file"
	chmod --reference "$file.old" "$file"
	touch --reference "$file.old" "$file"

	return 0
}




# (MAIN)

file="$HOME/.rdp.credentials"
magic="##ENCRYPTED##"
comment="#  use '$CMD decode/get' to read content"
action=

while [ $# != 0 ]
do
  case $1 in
   -*)	usage ;;
   *)	break ;;
  esac
  shift
done

[ $# -lt 0 ] && usage "too many parms"
[ $# -lt 1 ] && usage "'action' is mandatory"
action=$1; shift

[ $# = 1 ] && {
	file=$1
	shift
}
[ $# != 0 ] && usage "too many parms"

[ -f "$file" ] || {
	echo -e "\n$CMD error: file not found: '$file'\n" >&2
	exit 1
}

trap 'echo -e "\n*INTR*\n"; exit 255' 1 2 3
trap 'echo -e "\nunexpected error $? at $LINENO\n"' ERR
#trap 'cleanup' EXIT


case $action in
  get)
	decode_credentials
	;;
  crypt|encode)
	crypt_file || exit $?
	;;
  decrypt|decode)
	decrypt_file || exit $?
	;;
  edit)
	EDITOR=${EDITOR:-vi}
	decrypt_file || exit $?
	$EDITOR $file
	crypt_file || exit $?
	;;
esac

exit 0
