#!/bin/csh -f
set OPENSSL=/usr/bin/openssl
if ($#argv < 3) then
	echo 'Usage: decryptit key dest videofile [videofile] ...'
	echo 'Set dest to "." to place in the current directory'
	echo 'videofile may be specified with or without the aes-256 extension'
	exit 0
endif
set Keyval=$argv[1]
shift
set Dest=$argv[1]
shift
if ($Dest == "") then
	set Dest="."
endif
cat >/tmp/awk.$$ <<'EOF'
{ if (substr($1, 1, 2) == "0x" || substr($1, 1, 2) == "0X") {
if (length($1) != 18) { printf "Bad key length %d should be 16 digits\n",
length($1) - 2; exit 1; } for (i = 3; i <= length($1); i++) {
val = substr($1, i, 1); if ((val >= "0" && val <= "9") ||
(val >= "A" && val <= "F") || (val >= "a" && val <= "f")) continue;
printf "%s: digit %d of key has invalid value (%s)\n", $1, i - 2, val;
exit 1; } print substr($1, 3, 16); exit 0; } else {
printf "Bad key %s: key must start with 0x\n", $1; exit 1; } }
'EOF'
if (-e $Keyval) then
	set Key=`awk -f /tmp/awk.$$ $Keyval`
	set valid=$status
else
	echo $Keyval >/tmp/key.$$
	set Key=`awk -f /tmp/awk.$$ /tmp/key.$$`
	set valid=$status
	rm /tmp/key.$$
endif
rm /tmp/awk.$$
if ($valid != 0) then
	echo 0x$Key
	exit $valid
endif
echo Using key 0x$Key
foreach file ($*)
	set destfile=`basename $file`
	if ($file:e == "aes-256") then
		echo Decrypting $file to $Dest/$destfile:r
		$OPENSSL enc -d -aes-256-cbc -iv 0 -K $Key -in $file \
		    -out $Dest/$destfile:r
		touch -r $file $Dest/$destfile:r
	else
		echo Decrypting $file.aes-256 to $Dest/$destfile
		$OPENSSL enc -d -aes-256-cbc -iv 0 -K $Key -in $file.aes-256 \
		    -out $Dest/$destfile
		touch -r $file.aes-256 $Dest/$destfile
	endif
end
