#!/bin/bash
# See README.txt for documentation.
# Author: Jason Eisner <jason@cs.jhu.edu>

KEYFILE=german/gpw/gpw.cd   # File from which we're to derive the key.  Name may contain spaces or other special chars.

if (( $# < 1 || $# > 2 )); then
    # Wrong number of arguments
    echo 'Usage: $0 dataset.zip [keyfile]'
    exit 1
else
    # Try to set KEYPATH to the relative or absolute path of KEYFILE.
    # We look for KEYFILE under the current directory or under $2 if defined;
    # failing that, we look for just its basename in those places;
    # failing that, perhaps $2 is the whole path to KEYFILE;
    # failing that, we try to use the locate command if it exists.
    # 
    # Remark: If we omitted the quotes below, globbing chars could be included in KEYFILE.

    for KEYPATH in "${2:-.}/$KEYFILE" \
	           "${2:-.}/${KEYFILE##*/}" \
                   ${2:+"$2"} \
                   $(which locate >/dev/null && locate --limit 1 "*/$KEYFILE"); do
	if [[ -e $KEYPATH ]]; then 
	    # We found the keyfile.  So compute the key by hashing the keyfile, 
	    # and extract everything from zipfile $1 (except for README.txt and
	    # this script).
	    echo Hashing your licensed copy of $KEYPATH to get decryption key ... >&2
	    set -o pipefail
	    KEY=$(sha256sum "$KEYPATH" | gawk '{print $1}') &&
  	      unzip -P $KEY $1 -x README.txt ${0##*/}
	    exit 0
	fi
    done
    cat <<EOF 
Couldn't find your CELEX2 files.  Please re-run as
   $0 $1 CELEXPATH
where CELEXPATH is the directory that contains file $KEYFILE .
EOF
fi
