#!/bin/bash -e
#
# Purpose:
#  This script is responsible for determining the owner of a gerrit
#  commit, verifying they are within an approved gerrit group, and
#  then updating gerrit with that verification info.
#
# Note: It is assumed this script is run as a part of a jenkins job triggered
#       by the gerrit plugin. Therefore it assumes certain env variables
#       provided by that plugin are available (i.e. GERRIT_PROJECT, ...)
#
# Required Inputs:
#  SSH_KEY:  Path to private ssh key used to post messages to gerrit

GERRIT_COMMAND="curl -s --anyauth -n https://gerrit.openbmc.org"
GERRIT_SSH_CMD=( \
        ssh -o 'StrictHostKeyChecking no' -i "$SSH_KEY" \
        -p 29418 jenkins-openbmc-ci@gerrit.openbmc.org gerrit \
    )

echo "Checking ${GERRIT_PROJECT}:${GERRIT_BRANCH}:${GERRIT_CHANGE_ID}:${GERRIT_PATCHSET_REVISION}"

COMMITTER_USERNAME=$("${GERRIT_SSH_CMD[@]}" query "${GERRIT_CHANGE_NUMBER}" --current-patch-set --format json | jq -r '.currentPatchSet.uploader.username | select (. != null )')
echo "USERNAME: $COMMITTER_USERNAME"
if [ "${COMMITTER_USERNAME}" = "" ]; then
    echo "Unable to determine github user for ${COMMITTER_EMAIL}."
    "${GERRIT_SSH_CMD[@]}" review \
        "${GERRIT_CHANGE_NUMBER},${GERRIT_PATCHSET_NUMBER}" \
        --ok-to-test=0 "--message='Unable to determine github user'"
    exit 1
fi

# Reset the vote to 0 so jenkins will detect a new +1 on retriggers
"${GERRIT_SSH_CMD[@]}" review \
    "${GERRIT_CHANGE_NUMBER},${GERRIT_PATCHSET_NUMBER}" \
    --ok-to-test=0 -t autogenerated:jenkins --notify=NONE

# Add reviewers based on OWNERS files.
"${WORKSPACE}/openbmc-build-scripts/tools/owners" -p "${WORKSPACE}" reviewers |
{
    while read -r reviewer ;
    do
        # shellcheck disable=2086 # GERRIT_COMMAND is purposefully wordsplit.
        ${GERRIT_COMMAND}/a/changes/${GERRIT_PROJECT/\//%2F}~${GERRIT_BRANCH}~${GERRIT_CHANGE_ID}/reviewers \
            -X POST \
            -H "Content-Type: application/json" \
            -d "$reviewer" || true
    done
} || true

# Write full list of users to a file
GERRIT_CI_GROUPS=( \
        aimvalley/ci-authorized \
        akamai/ci-authorized \
        alibaba/ci-authorized \
        amd/ci-authorized \
        ami/ci-authorized \
        ampere/ci-authorized \
        arm/ci-authorized \
        aspeed/ci-authorized \
        asus/ci-authorized \
        bytedance/ci-authorized \
        celestica/ci-authorized \
        code-construct/ci-authorized \
        coreweave/ci-authorized \
        cornelis/ci-authorized \
        dell/ci-authorized \
        depo/ci-authorized \
        erg/ci-authorized \
        equinix/ci-authorized \
        facebook/ci-authorized \
        fii/ci-authorized \
        gagar-in/ci-authorized \
        google/ci-authorized \
        hcl/ci-authorized \
        hetzner/ci-authorized \
        hp/ci-authorized \
        hpe/ci-authorized \
        ibm/ci-authorized \
        iei/ci-authorized \
        individual/ci-authorized \
        ingrasys/ci-authorized \
        inspur/ci-authorized \
        intel/ci-authorized \
        inventec/ci-authorized \
        lenovo/ci-authorized \
        microsoft/ci-authorized \
        mitac/ci-authorized \
        multicoreware/ci-authorized \
        napatech/ci-authorized \
        nineelements/ci-authorized \
        nuvoton/ci-authorized \
        nvidia/ci-authorized \
        openbmc/ci-authorized \
        pcpartner/ci-authorized \
        phytium/ci-authorized \
        plexus/ci-authorized \
        qualcomm/ci-authorized \
        quanta/ci-authorized \
        quic/ci-authorized \
        raptorcs/ci-authorized \
        scaleway/ci-authorized \
        sipearl/ci-authorized \
        supermicro/ci-authorized \
        tencent/ci-authorized \
        tenstorrent/ci-authorized \
        triple-crown/ci-authorized \
        ufispace/ci-authorized \
        vaisala/ci-authorized \
        wistron/ci-authorized \
        wiwynn/ci-authorized \
    )

rm -f "$WORKSPACE/users.txt"
for g in "${GERRIT_CI_GROUPS[@]}"; do
    "${GERRIT_SSH_CMD[@]}" ls-members "$g" --recursive \
        >> "$WORKSPACE/users.txt"
done

# grep for the specific username word in the file
if grep -q -w "${COMMITTER_USERNAME}" "$WORKSPACE/users.txt"; then
    "${GERRIT_SSH_CMD[@]}" review \
        "${GERRIT_CHANGE_NUMBER},${GERRIT_PATCHSET_NUMBER}" \
        --ok-to-test=1 -t autogenerated:jenkins --notify=NONE \
        "--message='User approved, CI ok to start'"

    # Immediately erase the score to prevent infinite triggers.
    "${GERRIT_SSH_CMD[@]}" review \
        "${GERRIT_CHANGE_NUMBER},${GERRIT_PATCHSET_NUMBER}" \
        --ok-to-test=0 -t autogenerated:jenkins --notify=NONE

    exit 0
fi

echo "${COMMITTER_USERNAME} is not on the approved list."
"${GERRIT_SSH_CMD[@]}" review \
    "${GERRIT_CHANGE_NUMBER},${GERRIT_PATCHSET_NUMBER}" \
    --ok-to-test=0 -t autogenerated:jenkins \
    "--message='User not approved, see admin, no CI'"

exit 0
