#!/usr/bin/bash
#
# Copyright (C) 2024-2026 Red Hat, Inc.
#
# 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.

# send comment to all the parts of the change

set -ex

# Check for required arguments
if [ $# -ne 2 ]; then
    echo "Usage: $0 <DIR> <comment>"
    exit 1
fi

DIR="$1"
COMMENT="$2"

TOPDIR=$(cd $(dirname $0); pwd)

if [[ $0 =~ .*-podman$ ]]; then
    SUFFIX=-podman
else
    SUFFIX=
fi

if [ -r "$TOPDIR/common$SUFFIX" ]; then
    BASEDIR="$TOPDIR"
else
    BASEDIR=/usr/share/dci-pipeline
fi

. "$BASEDIR/common$SUFFIX"

# verify directory exists
if [ ! -d "$DIR" ]; then
    echo "Directory $DIR does not exist"
    exit 1
fi

# process all the json files representing the various parts of the change
for json in $(ls $DIR/*.json); do
    # Gerrit
    if [ $(jq -r .url $json) = null ]; then
        if [ -z $GERRIT_SSH_LOGIN ] || [ -z $GERRIT_SSH_ID ]; then
          echo "GERRIT_SSH_LOGIN or GERRIT_SSH_ID are not defined, the review is not updated"
          continue
        fi

        CHANGEID=$(jq -r ._number $json)
        CURREV=$(jq -r .current_revision $json)
        PATCHSET=$(jq -r ".revisions[\"$CURREV\"]._number" $json)
        GERRIT_JSON="{\"message\":\"${COMMENT}\",\"tag\":\"autogenerated:dci-change\"}"

        # Use json to allow message to be formatted
        echo "$GERRIT_JSON" |
          ssh \
          -i ~/.ssh/"$GERRIT_SSH_ID" \
          -p 29418 \
          "${GERRIT_SSH_LOGIN}@softwarefactory-project.io" \
            gerrit review -j "$CHANGEID,$PATCHSET"
    # Github PR or merge queue branch
    else
        REPO_NAME=$(jq -r .base.repo.name $json)

        if [[ -n "$GITHUB_NO_COMMENT_REPOS" && "$REPO_NAME" =~ $GITHUB_NO_COMMENT_REPOS ]]; then
            continue
        fi

        FULL_NAME=$(jq -r .head.repo.full_name $json)
        REPO_TOKEN=$($BASEDIR/get-config-entry "https://github.com/$FULL_NAME" github_token "$GITHUB_TOKEN")
        COMMENT_URL=$(jq -r .comments_url $json)
        GH_HEADERS=(
          "Accept: application/vnd.github.v3+json"
          "X-GitHub-Api-Version: 2022-11-28"
        )

        if [ -n "$REPO_TOKEN" ]; then
            GH_HEADERS+=("Authorization: token ${REPO_TOKEN}")
        fi

        # post the comment
        curl -s "${GH_HEADERS[@]/#/-H}" -X POST -d "{\"body\":\"${COMMENT}\"}" "$COMMENT_URL"
    fi

done

# send_comment ends here
