#!/usr/bin/bash
# Update various generated artifacts in rpm packages.
# This should be run in the directory containing the spec file.
# * Go vendor archive and config
# * COPR source file

shopt -s extglob

usage() {
    echo "Usage: $0 [OPTION]... <SPEC_FILE>"
    echo "Update generated artifacts belonging to the <SPEC_FILE>."
    echo
    echo "Options:"
    echo "  -u Ignore unlicensed mods"
    echo "  -h Print this message and exit"
    exit ${1:0}
}

while getopts ":uh" flag; do
    case "$flag" in
        u) IGNORE_UNLICENSED_ARG="-u ";;
        h) usage;;
        *) echo "Option $flag is unrecognized"; usage 1;;
    esac
done

SPEC_FILE="${@:$OPTIND:1}"

if [ "$SPEC_FILE" == "" ] || ! [[ "$SPEC_FILE" =~ .*.\.spec$ ]] || [ ! -f "$SPEC_FILE" ]; then
    echo "Required spec parameter missing or not a readable file ending in .spec"
    echo
    usage 1
fi

# Ensure remote sources are downloaded
spectool -g "$SPEC_FILE"

# go2rpm creates a go-vendor-tools.toml file when using the vendor profile
if grep -q go-vendor-tools.toml "$SPEC_FILE"; then
    echo Updating go vendor archive
    go2rpm-vendor-update "$IGNORE_UNLICENSED_ARG""$SPEC_FILE"
fi

# Update the sources checksums
# We assume all files are lowercase except README and LICENSE files
# The spec file itself is excluded
echo Calculating checksums
cksum -a sha512 !(sources|*.spec|RPMS|SRPMS|BUILD) > sources
echo Done
