#!/usr/bin/env bash

# Exit immediately if a any command exits with a non-zero status
# e.g. pull-request merge fails because of conflict
set -e

SOURCE_BRANCH=$1
DEST_BRANCH=$2
TITLE=$3
DESCRIPTION=$4
MERGE_STRATEGY=$5
CLOSE_SOURCE_BRANCH=$6

generate_create_data() {
  cat <<EOF
{
  "title": "$TITLE",
  "description": "$DESCRIPTION",
  "state": "OPEN",
  "destination": {
    "branch": {
      "name": "$DEST_BRANCH"
    }
  },
  "source": {
    "branch": {
      "name": "$SOURCE_BRANCH"
    }
  }
}
EOF
}

generate_merge_data() {
  cat <<EOF
{
  "message": "'$DESCRIPTION'",
  "close_source_branch": $CLOSE_SOURCE_BRANCH,
  "merge_strategy": "$MERGE_STRATEGY"
}
EOF
}
# Create new pull request and get its ID
echo "Creating PR: $SOURCE_BRANCH -> $DEST_BRANCH"
CREATE_URL=https://api.bitbucket.org/2.0/repositories/$BITBUCKET_REPO_OWNER/$BITBUCKET_REPO_SLUG/pullrequests
echo $CREATE_URL
PR_ID=`curl -X POST $CREATE_URL \
  --fail --show-error --silent \
  --user modea-integrator:$MODEA_INTEGRATOR_SECRET \
  -H 'content-type: application/json' \
  -d "$(generate_create_data)" \
  | sed -E "s/.*\"id\": ([0-9]+).*/\1/g"`

# Merge PR
echo "Merging PR: $PR_ID"
MERGE_URL=https://api.bitbucket.org/2.0/repositories/$BITBUCKET_REPO_OWNER/$BITBUCKET_REPO_SLUG/pullrequests/$PR_ID/merge
echo $MERGE_URL
curl -X POST $MERGE_URL \
  --fail --show-error --silent \
  --user modea-integrator:$MODEA_INTEGRATOR_SECRET \
  -H 'content-type: application/json' \
  -d "$(generate_merge_data)"




