#!/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
}

teardown(){
  _undeploy_app
  _reset_app
  _reset_recipe
}

@test "deploy then rollback" {
  run $ABRA app deploy "$TEST_APP_DOMAIN" "0.2.0+1.21.0" \
    --no-input --no-converge-checks
  assert_success

  run $ABRA app rollback "$TEST_APP_DOMAIN" "0.1.0+1.20.0" \
    --no-input --no-converge-checks
  assert_success

  assert_output --partial 'DOWNGRADE OVERVIEW'
  assert_output --partial 'CURRENT DEPLOYMENT    0.2.0+1.21.0'
  assert_output --partial 'ENV VERSION           0.2.0+1.21.0'
  assert_output --partial 'NEW DEPLOYMENT        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 "force rollback" {
  run $ABRA app deploy "$TEST_APP_DOMAIN" "0.2.0+1.21.0" \
    --no-input --no-converge-checks
  assert_success

  run $ABRA app rollback "$TEST_APP_DOMAIN" "0.2.0+1.21.0" \
    --no-input --no-converge-checks --force
  assert_success

  assert_output --partial 'REDEPLOY OVERVIEW'
  assert_output --partial 'CURRENT DEPLOYMENT    0.2.0+1.21.0'
  assert_output --partial 'ENV VERSION           0.2.0+1.21.0'
  assert_output --partial 'NEW DEPLOYMENT        0.2.0+1.21.0'

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

@test "app rollback no .env version" {
  run $ABRA app deploy "$TEST_APP_DOMAIN" "0.2.0+1.21.0" \
    --no-input --no-converge-checks
  assert_success

  _wipe_env_version

  run $ABRA app rollback "$TEST_APP_DOMAIN" "0.1.0+1.20.0" \
    --no-input --no-converge-checks
  assert_success

  assert_output --partial 'DOWNGRADE OVERVIEW'
  assert_output --partial 'CURRENT DEPLOYMENT    0.2.0+1.21.0'
  assert_output --partial 'ENV VERSION           N/A'
  assert_output --partial 'NEW DEPLOYMENT        0.1.0+1.20.0'

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