#!/bin/bash

# Check if both PR number and URL are provided
if [ -z "$1" ] || [ -z "$2" ]; then
  echo "Usage: $0 <PR_NUMBER> <REPOSITORY_URL>"
  echo "Example: $0 2 https://github.com/momentpay/terminalmanagement.git"
  exit 1
fi

PR_NUMBER="$1"
REPO_URL="$2"
FOLDER_NAME="pr-${PR_NUMBER}-folder" # Dynamic folder name based on PR number
PR_BRANCH_NAME="pr-${PR_NUMBER}"     # Dynamic branch name based on PR number

echo "Cloning repository: $REPO_URL into $FOLDER_NAME"
git clone "$REPO_URL" "$FOLDER_NAME"

if [ $? -ne 0 ]; then
  echo "Error: Failed to clone the repository."
  exit 1
fi

echo "Changing directory to: $FOLDER_NAME"
cd "$FOLDER_NAME"

if [ $? -ne 0 ]; then
  echo "Error: Failed to change directory to $FOLDER_NAME."
  exit 1
fi

echo "Fetching pull request $PR_NUMBER into branch $PR_BRANCH_NAME"
git fetch origin "pull/$PR_NUMBER/head:$PR_BRANCH_NAME"

if [ $? -ne 0 ]; then
  echo "Error: Failed to fetch pull request $PR_NUMBER."
  exit 1
fi

echo "Checking out branch: $PR_BRANCH_NAME"
git checkout "$PR_BRANCH_NAME"

if [ $? -ne 0 ]; then
  echo "Error: Failed to checkout branch $PR_BRANCH_NAME."
  exit 1
fi

echo "Successfully cloned and checked out PR #$PR_NUMBER in folder $FOLDER_NAME."

sudo chown -R www-data:www-data *
