#!/usr/bin/env bash

_dir=$(pwd)
DISTR_DIR=""
CERTIFICATE=""
SIGN_FILE="$HOME/sign_distr/distr.sign"

function parse_arguments() {
    while [ "${1}" != "" ]; do
        case "${1}" in
        -d | --dir)
            shift
            DISTR_DIR="${1}"
            ;;
        -c | --cert)
            shift
            CERTIFICATE="${1}"
            ;;
        -s | --sign)
            shift
            SIGN_FILE="${1}"
            ;;       
        -h | --help | help)
            usage
            exit 0
            ;;
        *)
            echo "ERROR: wrong script option: '${1}'"
            usage
            exit 1
            ;;
        esac
        shift
    done
}


function usage() {
    cat <<EOF
$(basename "${BASH_SOURCE[0]}") - verify dir sign.


SYNOPSIS
    $(basename "${BASH_SOURCE[0]}") [OPTIONS]


OPTIONS SUMMARY
    -h, --help      print this help
    -d, --dir       set dir with files for sign
    -c, --cert      set certificate with public key
    -s, --sign      set file with sign
    

EXAMPLES
    ./$(basename "${BASH_SOURCE[0]}") --dir ~/Downloads/distr-ac --cert cert.pem --sign ~/distr.sign   
EOF
}

parse_arguments "$@"

cd $DISTR_DIR
mkdir -p ~/verify_distr_sign/
find . -type f -print0 | sort -z | xargs -0 md5sum > ~/verify_distr_sign/distr.md5
cd $_dir
openssl dgst -sha256 -verify  <(openssl x509 -in $CERTIFICATE  -pubkey -noout) -signature $SIGN_FILE ~/verify_distr_sign/distr.md5
