#!/usr/bin/env bash

_latest_release(){
  echo $(git -C "$ABRA_DIR/recipes/$TEST_RECIPE" tag -l | tail -n 1)
}

_fetch_recipe() {
  if [[ ! -d "$ABRA_DIR/recipes/$TEST_RECIPE" ]]; then
    run mkdir -p "$ABRA_DIR/recipes"
    assert_success

    run git clone "https://git.coopcloud.tech/coop-cloud/$TEST_RECIPE" "$ABRA_DIR/recipes/$TEST_RECIPE"
    assert_success
  fi
}

_reset_recipe(){
  run rm -rf "$ABRA_DIR/recipes/$TEST_RECIPE"
  assert_success
  assert_not_exists "$ABRA_DIR/recipes/$TEST_RECIPE"

  _fetch_recipe
}

_ensure_latest_version(){
  latestRelease=$(_latest_release)

  if [ ! $latestRelease = "$1" ]; then
    echo "expected latest recipe version of '$1', saw: $latestRelease"
    return 1
  fi
}

_ensure_catalogue(){
  if [[ ! -d "$ABRA_DIR/catalogue" ]]; then
    run git clone https://git.coopcloud.tech/coop-cloud/recipes-catalogue-json.git $ABRA_DIR/catalogue
    assert_success
  fi
}

_ensure_env_version(){
  run sed -i 's/TYPE=abra-test-recipe:.*/TYPE=abra-test-recipe:$1/g' \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success
}

_wipe_env_version(){
  run sed -i 's/TYPE=abra-test-recipe:.*/TYPE=abra-test-recipe/g' \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success
}
