#!/bin/csh -f
# Takes a file from qf-encrypt and converts it back:
#
#     uuencode -> qf-des -> uncompress -> tar

# Usage:
#
#    qf-decrypt <qf-encrypt-file>
#
# You will be promted for a password to be used as a key and an another word to
# be used as an init vector for CBC mode DES. The init vector is optional -
# simply press return if you do not wish to specify one.

# Change this for your site, if required.
# Don't need full path names, really ...
set des        = "/cs/research/midas4/grappa/saleem/bin/sun4/qf-des"
set tar        = "/usr/bin/tar"
set uncompress = "/usr/ucb/uncompress"
set uudecode   = "/usr/bin/uudecode"
set awk        = "/usr/bin/awk"
set tmp        = "/tmp"

# Don't change anything below this line.
# (Actually, I'm sure this can all be coded better.)
if ($#argv != 1) then
   echo "usage: qf-decrypt <qf-encrypt-file>"
   exit 0
endif

if (!(-e $1)) then
    echo "No such file - $1"
    exit 0
endif

set ok = ""
while(${ok} != "y")

    set password = ""
    set ivstring = ""

    while(${password} == "")
        echo -n "Password: "
        set password = $<
    end

    echo -n "I Vector: "
    set ivstring = $<

    set ok = ""
    while((${ok} != "y") && (${ok} != "n") && (${ok} != "q"))
        echo -n "OK [y|n|q]? "
        set ok = $<
        if (${ok} == "q") then
            exit 0
        endif
    end
end

set mFile = `${awk} - '{if ($1) {if (substr($1, 0, 5) != "begin") {next;} else {print $3; exit;}}}' < $1`

set file = "${tmp}/.qf-d-$$"
set tFile = "${file}.tar"
set cFile = "${tFile}.Z"
set dFile = "${cFile}.des"

set tar = "${tar} xvf"
if (${ivstring} == "") then
    set des = "${des} -d -m cbc -p ${password}"
else
    set des = "${des} -d -m cbc -p ${password} -s ${ivstring}"
endif

# Do it - can I do this without all the tmp files and still get a check at each
# stage?
umask 077 # protect any files created

echo -n "  - uudecode ... "
if (! ({(${uudecode} $1)})) then
    echo "could not uudecode $1"
    goto _error_
endif
echo "ok"

if (! ({(mv ${mFile} ${dFile})})) then
    echo "could not mv ${mFile} to ${cFile}"
    goto _error_
endif

echo -n "  - decrypt ... "
if (! ({(${des} < ${dFile} > ${cFile})})) then
    echo "qf-des failed"
    goto _error_
endif
echo "ok"
rm -f ${dFile}

echo -n "  - uncompress ... "
if (! ({(${uncompress} ${cFile})})) then
    echo "could not uncompress ${cFile}"
    goto _error_
endif
echo "ok"

echo "  - tar ..."
if (! ({(${tar} ${tFile})})) then
    echo "could not extract files from tar file ${tFile}"
    goto _error_
endif
echo "  - ... ok"

goto _exit_

_error_:
echo "qf-decrypt failed"

_exit_:
rm -f ${tFile}* >& /dev/null
exit 0
