summaryrefslogtreecommitdiff
path: root/bash/denominate-function.bash
blob: 9e5cb3168f78e6e214cdbf7cce9dbf204790760e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/bin/bash
denominate_function()
{
	declare -n func_name="$1"
	local func_output_b64encoded output_hash
	read -r -d '' \
		func_output_b64encoded \
		< <(base64) || [ "${func_output_b64encoded}" ]
	read output_hash _ \
		< <(base64 -d <<< "$func_output_b64encoded" | sha256sum)
	[ ${#output_hash} = 64 ] || return
	func_name=SHA256_${output_hash:0:32}
	source <(cat <<END
${func_name} ()
{
base64 -d <<.
${func_output_b64encoded}
.
}
END
)
}

reverse_hash()
{
	case "$#.$1" in
	2.SHA256 )
		;;
	1.SHA256_???????????????????????????????? )
		set -- SHA256 "${1#SHA256_}"
		;;
	* )
		return 1
		;;
	esac
	case ${#2} in
	32 | 64 )
		set -- "${1}_${2: 0 : 32}"
		;;
	* )
		return 1
		;;
	esac
	(
		set -o pipefail
		set -e
		declare -f "$1" |
		sed -n -e '/^[	 ]*base64 -d <<[.]$/,/^[.]$/ { p }' |
		sed -e '1 d ; $ d' |
		base64 -d
	)
}

example_input()
{
	sed -n -e '/^reverse_hash *()/ , /^}$/ p' <"$0"
}

set -e
set -o pipefail

if [ -t 0 ]
then
	if [ $# = 0 ]
	then
		denominate_function f < <(example_input)
	else
		denominate_function f <<< "$*"
	fi
else
	denominate_function f
fi

read -r -d '' < <( reverse_hash "$f" | base64) || [ "$REPLY" ]
if	read s _ < <( base64 -d <<< "$REPLY" | sha256sum ) &&
	[ ${#s} -eq 64 -a "${s: 0 : 32}" = "${f: -32 : 32}" ]
then
	declare -f "$f" | grep . &&
	printf '%s\n' "$f"
else
	false
fi