#!/bin/sh
# ------------------------------------------------------------------------------
# Programmer(s): Cody J. Balos @ LLNL
# ------------------------------------------------------------------------------
# SUNDIALS Copyright Start
# Copyright (c) 2002-2019, Lawrence Livermore National Security
# and Southern Methodist University.
# All rights reserved.
#
# See the top-level LICENSE and NOTICE files for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# SUNDIALS Copyright End
# -----------------------------------------------------------------------------
# Grabs a pull-request from the SUNDIALS Github repository, converts it to
# a patch, and then applies it.
# -----------------------------------------------------------------------------

if [ $# -eq 0 ] || [ "$1" = "-help" ]; then
  echo ""
  echo "./applyGithubPR -help | <pull request url>"
  echo ""
  echo "where:"
  echo ""
  echo "  -help       displays this message"
  echo ""
  echo "example usage: ./applyGithubPR https://github.com/LLNL/sundials/pull/12"
  exit 1
fi

PR_URL=$1
PR_NUMBER=${PR_URL##*/}
PATCH_URL="${PR_URL}.patch"
PATCH_FILE="github-PR-$PR_NUMBER.patch"

# grab the patch from Github
wget $PATCH_URL -O ../$PATCH_FILE -o /dev/null

# output some information about the patch and ensure the user wants to apply it
echo "pull-request converted to patch file ../${PATCH_FILE}"
echo "current git branch: $(git rev-parse --abbrev-ref HEAD)"
echo "pull-request changes:"
echo ""
cd ../ && git apply --stat $PATCH_FILE
echo ""
read -p "Do you want to apply the pull-request? [y/n] " yn

if [ "$yn" = "y" ]; then
  git am --signoff < $PATCH_FILE
  rm $PATCH_FILE
  echo "successfully applied pull-request ${PR_URL}"
else
  echo "pull-request ${PR_URL} not applied"
fi

