#!/bin/sh

targetBranch='heads/'$1
sourceBranch='heads/'$2
githubRepo=$3
token=$4

echo $targetBranch
echo $sourceBranch
echo $githubRepo

targetResp=`curl -H "Accept: application/vnd.github+json" -H "Authorization: token ${token}" https://api.github.com/repos/${githubRepo}/git/ref/${targetBranch}`
msg=`echo ${targetResp} | jq -c -r '.message'`
echo $msg

sourceResp=`curl -H "Accept: application/vnd.github+json" -H "Authorization: token ${token}" https://api.github.com/repos/${githubRepo}/git/ref/${sourceBranch}`
sha=`echo ${sourceResp} | jq -c -r '.object.sha'`
echo $sha

if [ "$msg" = 'Not Found' ];then
# Create branch if not exist
    curl -X POST \
        -H "Accept: application/vnd.github+json" \
        -H "Authorization: token ${token}" \
        https://api.github.com/repos/${githubRepo}/git/refs \
        -d '{"ref":"refs/'${targetBranch}'", "sha":"'${sha}'"}'
else
    # Update branch if exist
     curl -X PATCH \
        -H "Accept: application/vnd.github+json" \
        -H "Authorization: token ${token}" \
        https://api.github.com/repos/${githubRepo}/git/refs/${targetBranch} \
        -d '{"sha":"'${sha}'", "force": true}'
fi
