#!/bin/sh
#
# This script will walk the directory it is run from and verify the
# SHA-256 digests found in any 'SHA256' files.  You can use it to
# verify a mirrored release tree.
#
# {{{ Apache License version 2.0
#
# Copyright 2017 David Cantrell <david.l.cantrell@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# }}}

PATH=/bin:/usr/bin
CWD="$(realpath $(pwd))"
RET=0

for fname in $(find "$CWD" -type f -name SHA256) ; do
    dname="$(dirname $fname)"
    cd "$dname"
    while read first digest ; do
        filename="$(echo "$first" | cut -d '(' -f 2 | cut -d ')' -f 1)"
        computed="$(openssl dgst -sha256 "$filename" | rev | cut -d ' ' -f 1 | rev)"
        echo -n "$filename: "
        if [ "$digest" = "$computed" ]; then
            echo "OK"
        else
            echo "FAILED"
            RET=1
        fi
    done < SHA256
done

exit $RET
