#!/usr/bin/env bash

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

teardown_file(){
  _rm_app
  _rm_server
  _reset_recipe
}

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

teardown(){
  _reset_recipe
  _undeploy_app
  _reset_app
}

@test "deploy and undeploy" {
  run $ABRA app deploy "$TEST_APP_DOMAIN" "0.1.0+1.20.0" \
    --no-input --no-converge-checks
  assert_success

  run $ABRA app undeploy "$TEST_APP_DOMAIN" --no-input
  assert_success

  # current deployment
  assert_output --regexp 'VERSION.*' + "0.1.0+1.20.0" 
  assert_output --regexp 'CHAOS.*false'

  # env version
  assert_output --regexp 'CURRENT VERSION.*' + "0.1.0+1.20.0"
  assert_output --regexp 'NEW VERSION.*' + "0.1.0+1.20.0"

  run grep -q "TYPE=$TEST_RECIPE:0.1.0+1.20.0" \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success
}

@test "chaos deploy and undeploy" {
  headHash=$(_get_head_hash)
  latestRelease=$(_latest_release)

  run $ABRA app deploy "$TEST_APP_DOMAIN" \
    --no-input --no-converge-checks --chaos
  assert_success

  run $ABRA app undeploy "$TEST_APP_DOMAIN" --no-input
  assert_success

  # current deployment
  assert_output --regexp 'VERSION.*' + "${latestRelease}"
  assert_output --regexp 'CHAOS.*' + "${headHash:0:8}"

  # env version
  assert_output --regexp 'CURRENT VERSION.*' + "${latestRelease}"
  assert_output --regexp 'NEW VERSION.*' + "${headHash:0:8}"

  run grep -q "TYPE=$TEST_RECIPE:${headHash:0:8}" \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success
}

@test "chaos deploy with unstaged commits and undeploy" {
  headHash=$(_get_head_hash)
  latestRelease=$(_latest_release)

  run bash -c 'echo "unstaged changes" >> "$ABRA_DIR/recipes/$TEST_RECIPE/foo"'
  assert_success
  assert_exists "$ABRA_DIR/recipes/$TEST_RECIPE/foo"

  run $ABRA app deploy "$TEST_APP_DOMAIN" \
    --no-input --no-converge-checks --chaos
  assert_success

  run $ABRA app undeploy "$TEST_APP_DOMAIN" --no-input
  assert_success

  # current deployment
  assert_output --regexp 'VERSION.*' + "${latestRelease}"
  assert_output --regexp 'CHAOS.*' + "${headHash:0:8}+U"

  # env version
  assert_output --regexp 'CURRENT VERSION.*' + "${latestRelease}"
  assert_output --regexp 'NEW VERSION.*' + "${headHash:0:8}+U"

  run grep -q "TYPE=$TEST_RECIPE:${headHash:0:8}" \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success

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