#!/usr/bin/env bash

setup_file(){
  load "$PWD/tests/integration/helpers/common"
  _common_setup
  _add_server
  _new_app
}

teardown_file(){
  _rm_server
  _reset_recipe
}

setup(){
  load "$PWD/tests/integration/helpers/common"
  _common_setup
}

teardown(){
  _reset_recipe
}

@test "validate recipe argument" {
  run $ABRA recipe upgrade --no-input
  assert_failure

  run $ABRA recipe upgrade DOESNTEXIST --no-input
  assert_failure
}

@test "retrieve recipe if missing" {
  run rm -rf "$ABRA_DIR/recipes/$TEST_RECIPE"
  assert_success
  assert_not_exists "$ABRA_DIR/recipes/$TEST_RECIPE"

  run $ABRA recipe upgrade "$TEST_RECIPE" --no-input
  assert_success
  assert_output --partial 'can upgrade service: app'

  assert_exists "$ABRA_DIR/recipes/$TEST_RECIPE"
}

@test "error if unstaged changes" {
  run bash -c "echo foo >> $ABRA_DIR/recipes/$TEST_RECIPE/foo"
  assert_success
  assert_exists "$ABRA_DIR/recipes/$TEST_RECIPE/foo"

  run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" status
  assert_success
  assert_output --partial 'foo'

  run $ABRA recipe upgrade "$TEST_RECIPE" --no-input
  assert_failure
  assert_output --partial 'locally unstaged changes'

  assert_exists "$ABRA_DIR/recipes/$TEST_RECIPE/foo"
  assert_equal "$(_git_status)" "?? foo"

  run rm -rf "$ABRA_DIR/recipes/$TEST_RECIPE/foo"
  assert_not_exists "$ABRA_DIR/recipes/$TEST_RECIPE/foo"
}

@test "ensure up to date" {
  wantHash=$(_get_n_hash 3)

  run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" reset --hard HEAD~3
  assert_success

  assert_equal $(_get_current_hash) "$wantHash"

  run $ABRA recipe upgrade "$TEST_RECIPE" --no-input
  assert_success
  assert_output --partial 'can upgrade service: app'

  assert_equal $(_get_head_hash) $(_get_current_hash)
}

@test "only one of -x/y/z flags" {
  run $ABRA recipe upgrade "$TEST_RECIPE" --no-input -x -y
  assert_failure
  assert_output --partial 'you can only use one of'
}

@test "upgrade patch" {
  run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" checkout "0.2.0+1.21.0"
  assert_success

  assert_equal $(_get_tag_hash 0.2.0+1.21.0) $(_get_current_hash)

  run $ABRA recipe upgrade "$TEST_RECIPE" --no-input --patch
  assert_success

  run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" diff
  assert_success
  assert_output --partial 'image: nginx:1.21.6'
}

@test "upgrade minor" {
  run $ABRA recipe upgrade "$TEST_RECIPE" --no-input --minor
  assert_success

  run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" diff
  assert_success
  assert_output --regexp 'image: nginx:1.2.*'
}
