#!/bin/bash
set -e -o pipefail

commit=${GITHUB_SHA}
ref=${GITHUB_REF}
branch_ref_prefix="refs/heads/"
pr_ref_prefix="refs/pull/"
tag_ref_prefix="refs/tags/"

if [[ $commit == "" ]]; then
  echo "Missed commit sha"
  exit 1
fi

if [[ $ref == "$branch_ref_prefix"* ]]; then
  lenth=${#branch_ref_prefix}
  branch=${ref:$lenth}
  echo "checkout branch $branch with commit $commit"
  git fetch --no-tags --prune origin "+${commit}:refs/remotes/origin/${branch}"
  git checkout --progress --force -B "$branch" "refs/remotes/origin/${branch}"
elif [[ $ref == "$pr_ref_prefix"* ]]; then
  lenth=${#pr_ref_prefix}
  pr=${ref:$lenth}
  echo "checkout pull request $pr with commit $commit"
  git fetch --no-tags --prune origin "+${commit}:refs/remotes/pull/${pr}"
  git checkout --progress --force "refs/remotes/pull/${pr}"
elif [[ $ref == "$tag_ref_prefix"* ]]; then
  lenth=${#tag_ref_prefix}
  tag=${ref:$lenth}
  echo "checkout tag $tag with commit $commit"
  git fetch --no-tags --prune origin "+${commit}:${ref}"
  git checkout --progress --force "${ref}"
else
  git fetch --no-tags --prune origin "${commit}"
  git checkout --progress --force "${commit}"
  echo "checkout commit $commit"
fi
