#!/usr/bin/env bash

_dir=$(pwd)
DISTR_DIR="/WORKDIR/distr-ac"
CERTIFICATE="/etc/keys/ac/cacert.pem"
SIGN_FILE="/WORKDIR/distr.sign"
TEMP_DIR="/tmp/verify_distr_sign"
MD5_FILE="$TEMP_DIR/distr.md5"

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

# clean up
find . -type f -name .DS_Store | xargs rm -f
find . -type f -name ._* | xargs rm -f
find . -type f -name desktop.ini | xargs rm -f

mkdir -p $TEMP_DIR
find . -type f -print0 | LC_ALL=C sort -z | xargs -0 md5sum >$MD5_FILE
cd $_dir
openssl dgst -sha256 -verify <(openssl x509 -in $CERTIFICATE -pubkey -noout) -signature $SIGN_FILE $MD5_FILE
