#!/usr/bin/env bash

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

teardown_file(){
  _rm_server
}

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

teardown(){
  _reset_recipe
  _reset_tags
}

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

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

@test "allow unstaged changes" {
  run echo "unstaged changes" >> "$ABRA_DIR/recipes/$TEST_RECIPE/foo"
  assert_success

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

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

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

@test "detect unstaged label changes" {
  run $ABRA recipe fetch "$TEST_RECIPE"
  assert_success

  run $ABRA recipe sync "$TEST_RECIPE" --patch
  assert_success

  run $ABRA recipe sync "$TEST_RECIPE" --patch
  assert_success
  assert_output --partial 'is already set, nothing to do?'
}

@test "sync patch label bump" {
  _ensure_latest_version "0.3.0+1.21.0"

  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'

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

  run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" diff
  assert_success
  assert_output --regexp 'coop-cloud\.\$\{STACK_NAME\}\.version=0\.3\.1\+1\.2.*'
}

@test "sync minor label bump" {
  _ensure_latest_version "0.3.0+1.21.0"

  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.*'

  run $ABRA recipe sync "$TEST_RECIPE" --no-input --minor
  assert_success

  run git -C "$ABRA_DIR/recipes/$TEST_RECIPE" diff
  assert_success
  assert_output --regexp 'coop-cloud\.\$\{STACK_NAME\}\.version=0\.4\.0\+1\.2.*'
}

@test "error if --no-input and no initial version" {
  _remove_tags

  run $ABRA recipe sync "$TEST_RECIPE" --no-input --patch
  assert_failure
  assert_output --partial 'unable to continue'
  assert_output --partial 'initial version'
}

@test "output label sync only once" {
  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.*'

  run $ABRA recipe sync "$TEST_RECIPE" --no-input --minor
  assert_success
  assert_line --index 0 --partial 'synced label'
  refute_line --index 1 --partial 'synced label'
}
