#!/usr/bin/env bash
set -eo pipefail

main() {
  declare VERSION="$1" BOT_GITHUB_USERNAME="$2" BOT_GITHUB_API_TOKEN="$3"
  local GH_VERSION=1.6.1
  local DATE_UPDATED="$(date +"%Y-%m-%d")"
  local GH_FOLDER="gh_${GH_VERSION}_linux_amd64"

  echo "=====> Downloading gh"
  wget -O gh.tar.gz "https://github.com/cli/cli/releases/download/v${GH_VERSION}/${GH_FOLDER}.tar.gz"
  mkdir -p tmp
  tar xzf gh.tar.gz -C tmp
  if [[ ! -f tmp/$GH_FOLDER/bin/gh ]]; then
    echo "Failed to extract gh"
    return 1
  fi

  cd tmp

  if [[ -n "$BOT_GITHUB_API_TOKEN" ]]; then
    $GH_FOLDER/bin/gh auth login --with-token <<<"$BOT_GITHUB_API_TOKEN"
  else
    echo "BOT_GITHUB_API_TOKEN is not set, skipping gh auth login"
  fi

  echo "=====> Cloning quickstart templates"
  rm -rf azure-quickstart-templates >/dev/null
  git clone https://github.com/Azure/azure-quickstart-templates.git azure-quickstart-templates

  pushd azure-quickstart-templates >/dev/null

  echo "=====> Updating values"
  contents="$(jq '.githubUsername = "dokku"' application-workloads/dokku/dokku-vm/metadata.json)"
  echo "${contents}" >application-workloads/dokku/dokku-vm/metadata.json
  contents="$(jq --arg DATE_UPDATED "$DATE_UPDATED" '.dateUpdated = $DATE_UPDATED' application-workloads/dokku/dokku-vm/metadata.json)"
  echo "${contents}" >application-workloads/dokku/dokku-vm/metadata.json

  contents="$(jq --arg VERSION "$VERSION" '.parameters.dokkuVersion.defaultValue = $VERSION' application-workloads/dokku/dokku-vm/azuredeploy.json)"
  echo "${contents}" >application-workloads/dokku/dokku-vm/azuredeploy.json

  # update the version in main.bicep
  # the line being updated looks like this:
  # param dokkuVersion string = '0.28.4'
  # we need to update the value of dokkuVersion to the new version
  sed -i "s/param dokkuVersion string = '[^']*'/param dokkuVersion string = '$VERSION'/" application-workloads/dokku/dokku-vm/main.bicep

  echo "=====> Updating remote repository"
  git add application-workloads/dokku/dokku-vm
  git checkout -b dokku-$VERSION
  git commit -m "Update dokku-vm dokku version to $VERSION"
  if [[ -z "$BOT_GITHUB_API_TOKEN" ]] || [[ -z "$BOT_GITHUB_USERNAME" ]]; then
    echo "BOT_GITHUB_API_TOKEN or BOT_GITHUB_USERNAME is not set, skipping git remote set-url"
  else
    git remote set-url origin "https://$BOT_GITHUB_USERNAME:$BOT_GITHUB_API_TOKEN@github.com/dokku/azure-quickstart-templates.git"
    git push -f origin dokku-$VERSION
  fi

  if [[ -z "$BOT_GITHUB_API_TOKEN" ]] || [[ -z "$BOT_GITHUB_USERNAME" ]]; then
    echo "BOT_GITHUB_API_TOKEN or BOT_GITHUB_USERNAME is not set, skipping gh pr create"
  else
    echo "=====> Creating upstream pull request"
    ../$GH_FOLDER/bin/gh pr create --head dokku:dokku-$VERSION --repo Azure/azure-quickstart-templates --title "Update dokku-vm dokku version to $VERSION" --body ''
  fi

  popd &>/dev/null
}

main "$@"
