#!/usr/bin/bash

# Usage: $0 <source-dir> [<ref>]
# Example refs:
#  master
#  HEAD
#  mainstream/master
# Default ref: HEAD

[ "$DEBUG" = "1" ] && set -x

# shellcheck source=scripts/common
source "$BUILDER_DIR/scripts/common"

set -o pipefail

if [ "$NO_CHECK" == "1" ]; then
    exit 0
fi

if [ -n "$KEYRING_DIR_GIT" ]; then
    export GNUPGHOME="$(readlink -m "$KEYRING_DIR_GIT")"
    if [ ! -d "$GNUPGHOME" ]; then
        mkdir -p "$GNUPGHOME"
        chmod 700 "$GNUPGHOME"
        gpg --import qubes-developers-keys.asc
        # Trust Qubes Master Signing Key
        echo '427F11FD0FAA4B080123F01CDDFA1A3E36879494:6:' | gpg --import-ownertrust
    fi
    if [ qubes-developers-keys.asc -nt "$GNUPGHOME/pubring.gpg" ]; then
        gpg --import qubes-developers-keys.asc
        touch "$GNUPGHOME/pubring.gpg"
    fi
    maintainers=$(env | grep -oP '^ALLOWED_COMPONENTS_[a-fA-F0-9]{40}')
    for maintainer in $maintainers
    do
        allowed_components=("${!maintainer}")
        COMPONENT="$(basename "$1")"
        COMPONENT="${COMPONENT//./builder}"
        if elementIn "$COMPONENT" ${allowed_components[@]}; then
            keyid=${maintainer#ALLOWED_COMPONENTS_}
            gpg --import "$BUILDER_DIR/keys/$keyid.asc" || exit 1
            echo "$keyid:6:" | gpg --import-ownertrust
        fi
    done
    gpgconf --kill gpg-agent
fi

pushd "$1" > /dev/null || exit 2

if [ -n "$2" ]; then
    REF="$2"
else
    REF="HEAD"
fi

verify_tag() {
    content="$(git verify-tag --raw "$1" 2>&1)"
    newsig_number="$(echo "$content" | grep -o NEWSIG | wc -l)"
    if [ "$newsig_number" = 1 ] && { echo "$content" | grep -q '^\[GNUPG:\] TRUST_\(FULLY\|ULTIMATE\)'; }; then
        return 0
    else
        return 1
    fi
}

VALID_TAG_FOUND=0
for tag in $(git tag --points-at="$REF"); do
    if verify_tag "$tag"; then
        VALID_TAG_FOUND=1
    else
        if [ "0$VERBOSE" -ge 1 ]; then
            echo "---> One of signed tag cannot be verified:"
            git tag -v "$tag"
        fi
    fi
done

if [ "$VALID_TAG_FOUND" -eq 0 ]; then
    echo "No valid signed tag found!"
    if [ "0$VERBOSE" -eq 0 ]; then
        if [ -n "$(git describe "$REF")" ]; then
            echo "---> One of invalid tag:"
            git tag -v $(git describe "$REF")
        fi
    fi
    exit 1
fi

exit 0
