#!/bin/sh -e

if [ ! -f "$__object/parameter/sum" ]
then
    exit 0
fi

if [ -f "$__object/parameter/cmd-sum" ]
then
    cat "$__object/parameter/cmd-sum"
    exit 0
fi

sum_should="$( cat "$__object/parameter/sum" )"

if echo "$sum_should" | grep -Fq ':'
then
    sum_hash="$( echo "$sum_should" | cut -d : -f 1 )"
else
    if echo "$sum_should" | grep -Eq '^[0-9]+\s[0-9]+$'
    then
        sum_hash='cksum'
    elif
        echo "$sum_should" | grep -Eiq '^[a-f0-9]{32}$'
    then
        sum_hash='md5'
    elif
        echo "$sum_should" | grep -Eiq '^[a-f0-9]{40}$'
    then
        sum_hash='sha1'
    elif
        echo "$sum_should" | grep -Eiq '^[a-f0-9]{64}$'
    then
        sum_hash='sha256'
    else
        echo 'hash format detection failed' >&2
        exit 1
    fi
fi

os="$( "$__explorer/os" )"

case "$sum_hash" in
    cksum)
        echo "cksum %s | awk '{print \$1\" \"\$2}'"
    ;;
    md5)
        case "$os" in
            freebsd)
                echo "md5 -q %s"
            ;;
            *)
                echo "md5sum %s | awk '{print \$1}'"
            ;;
        esac
    ;;
    sha1)
        case "$os" in
            freebsd)
                echo "sha1 -q %s"
            ;;
            *)
                echo "sha1sum %s | awk '{print \$1}'"
            ;;
        esac
    ;;
    sha256)
        case "$os" in
            freebsd)
                echo "sha256 -q %s"
            ;;
            *)
                echo "sha256sum %s | awk '{print \$1}'"
            ;;
        esac
    ;;
    *)
        # we arrive here only if --sum is given with unknown format prefix
        echo "unknown hash format: $sum_hash" >&2
        exit 1
    ;;
esac
