#!/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(){
  _reset_recipe
  _undeploy_app
  _reset_app

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

@test "validate app argument" {
  run $ABRA app env list
  assert_failure

  run $ABRA app env list DOESNTEXIST
  assert_failure
}

@test "show env version" {
  latestRelease=$(_latest_release)

  run $ABRA app env list "$TEST_APP_DOMAIN"
  assert_success
  assert_output --partial "$latestRelease"
}

@test "show env version despite --chaos" {
  run bash -c "echo foo >> $ABRA_DIR/recipes/$TEST_RECIPE/foo"
  assert_success
  assert_exists "$ABRA_DIR/recipes/$TEST_RECIPE/foo"

  run $ABRA app env list "$TEST_APP_DOMAIN"
  assert_success

  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 "app env pull explodes when no deployed app" { 
  run $ABRA app env pull "$TEST_APP_DOMAIN" -s "$TEST_SERVER"
  assert_failure
}

# bats test_tags=slow
@test "app env pull recreates app env when missing" { 
  run $ABRA app deploy "$TEST_APP_DOMAIN" --no-input
  assert_success

  run rm -rf "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success
  assert_not_exists "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"

  run $ABRA app env pull "$TEST_APP_DOMAIN" -s "$TEST_SERVER"
  assert_success
  assert_exists "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
}

# bats test_tags=slow
@test "app env pull recreates correct version" { 
  run $ABRA app deploy "$TEST_APP_DOMAIN" "0.1.0+1.20.0" --no-input
  assert_success

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

  run rm -rf "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success
  assert_not_exists "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"

  run $ABRA app env pull "$TEST_APP_DOMAIN" -s "$TEST_SERVER"
  assert_success
  assert_exists "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"

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