#!/bin/bash

usage()
{
        echo "USAGE:________________";
        echo "mkmnpub -f dataset_file -k key_file -c mncrt_file  [-o out_file]";
        echo "-f  The path to the dataset";
        echo "-k  The path to the file containing the private key";
        echo "-o  The name of the output file. (Default: out.mnpub)";
        echo "-c  The path to the certificate file (mncrt).";
}

args=`getopt "o:f:k:c:" $*`
if [ $? != 0 ]
then
        usage
        exit 1
fi

_outname="out.mnpub";

set -- $args
while true
do
        case "$1"
        in
                -o)
                        _outname=$2;
                        shift 2;;
                -f)
                        _infile=$2;
                        shift 2;;
                -k)
                        _keyfile=$2;
                        shift 2;;
                -c)
                        _crtfile=$2;
                        shift 2;;
                --)
                        shift;
                        break;;
                *)
                        echo "Invalid option";
                        exit 2;;
        esac
done

if [ -z "$_infile" ]
then
        echo "An input file must be specified"
        usage
        exit 3
fi

if [ -z "$_keyfile" ]
then
        echo "A key file must be specified"
        usage
        exit 3
fi
if [ -z "$_crtfile" ]
then
        echo "A certificate file must be specified"
        usage
        exit 3
fi


if [ ! -f $_inFile ]
then
	echo Input file not found: $_infile
	exit 4
fi

if [ ! -f $_keyfile ]
then
        echo Key file not found: $_keyfile
        exit 4
fi

if [ ! -f $_crtfile ]
then
        echo Certificate file not found: $_crtfile
        exit 4
fi

_inbase=$(basename $_infile);
_signfile=${TMPDIR-~}/$_inbase.sign

# Create the signature
openssl dgst -binary -sha1 -sign $_keyfile -out $_signfile $_infile || exit 5

#_SIGNATURE=$(hexdump -ve '1/1 "%.2x"' $_signfile)
_SIGNATURE=$(base64 -w 0 $_signfile)

echo ----- MNOVA PUBLICATIONS FILE ----- > $_signfile
echo URL:$_inbase >> $_signfile
echo SIGNATURE:$_SIGNATURE >> $_signfile
cat $_signfile $_crtfile > $_outname
rm $_signfile
