#!/bin/bash -e
# gitPrCreate.sh
#
# Create git PR

branch=''
title=''
draft='false'

argumentsCount=$#
for(( argumentIndex=1; argumentIndex<=argumentsCount; argumentIndex+=2 )); do
  argumentKey=${!argumentIndex}
  argumentValueIndex=$((argumentIndex+1))
  argumentValue=${!argumentValueIndex}
  if [[ $argumentKey == "--branch" ]]; then
    branch=$argumentValue
  elif [[ $argumentKey == "--title" ]]; then
    title=$argumentValue
  elif [[ $argumentKey == "--draft" ]]; then
    draft=$argumentValue
  else
    echo "Unknown argument $argumentKey"
    exit 1
  fi
done

if [[ $branch == '' ]]; then
  echo "Missed argument: --branch [XYZ]"
  exit 1
fi
if [[ $title == '' ]]; then
  echo "Missed argument: --title [XYZ]"
  exit 1
fi
draftArg=''
if [ "$draft" == "true" ]; then
  draftArg='--draft'
elif [ "$draft" == "false" ]; then
  draftArg=''
else
  echo "Missed argument: --draft [true|false]"
  exit 1
fi


if [[ -z $(git status --porcelain) ]]; then
  echo "The Git repository is clean. PR cant be created."
  exit 1
fi


currentBranch=$(git symbolic-ref --short HEAD)

git checkout -b $branch
git add .
git commit -m "$title"
git push upstream $branch
git checkout $currentBranch
git branch -D $branch

upstreamUrl=$(git remote get-url upstream)
urlPath=${upstreamUrl#*:}
urlPath=${urlPath%.git}
upstreamOwner=${urlPath%/*}
upstreamRepo=${urlPath#*/}
gh pr create --title "$title" --body "" --base master --head $branch --repo $upstreamOwner/$upstreamRepo $draftArg

