#!/usr/bin/env bash

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

_fetch_recipe() {
  # clone first to a bare repo which will serve as origin-ssh
  # this enables simulating git push in recipe release
  if [[ ! -d "$ABRA_DIR/recipes/$TEST_RECIPE" ]]; then
    run mkdir -p "$ABRA_DIR/origin-recipes"
    assert_success

    run git clone "https://git.coopcloud.tech/toolshed/$TEST_RECIPE" "$ABRA_DIR/origin-recipes/$TEST_RECIPE.git" --bare
    assert_success

    run mkdir -p "$ABRA_DIR/recipes"
    assert_success

    run git clone "$ABRA_DIR/origin-recipes/$TEST_RECIPE.git" "$ABRA_DIR/recipes/$TEST_RECIPE"
    assert_success

    run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" remote add origin-ssh "$ABRA_DIR/origin-recipes/$TEST_RECIPE.git"
    assert_success
  fi
}

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

  run rm -rf "$ABRA_DIR/origin-recipes/$TEST_RECIPE.git"
  assert_success
  assert_not_exists "$ABRA_DIR/origin-recipes/$TEST_RECIPE.git"

  _fetch_recipe
}

_ensure_catalogue(){
  if [[ ! -d "$ABRA_DIR/catalogue" ]]; then
    run git clone https://git.coopcloud.tech/toolshed/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
}
