#!/bin/bash

set -ex

forgejo=$1
forgejo_pr=$2
xorm=$3
xorm_pr_or_ref=$4

#
# Get information from xorm
#
cd $xorm

module=code.forgejo.org/xorm/xorm
sha=$(git -C $xorm show --no-patch --format=%H)
test "$sha"

#
# Update Forgejo to use xorm at $xorm_pr_or_ref
#
cd $forgejo
#
# If it is a pull request, change the module to reference the forked repository so
# go mod tidy can find the SHA from a known branch or tag
#
if test -f "$xorm_pr_or_ref"; then
	repository=$(jq --raw-output .head.repo.full_name <$xorm_pr_or_ref)
	test "$repository"
	module=$(echo $module | sed -e "s|code.forgejo.org/xorm/xorm|code.forgejo.org/$repository|")
fi
#
# add a "replace code.forgejo.org/xorm/xorm" line to the forgejo go.mod
# so that it uses the branch or pull request from which the cascade is run.
#
sed -i -e "\|replace code.forgejo.org/xorm/xorm|d" go.mod
echo "replace code.forgejo.org/xorm/xorm => $module $sha" >>go.mod
go mod tidy
