#!/usr/bin/env bash

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

  # NOTE(d1): create new app without secrets
  run $ABRA app new "$TEST_RECIPE" \
    --no-input \
    --server "$TEST_SERVER" \
    --domain "$TEST_APP_DOMAIN"
  assert_success
  assert_exists "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
}

teardown_file(){
  _rm_app
  _rm_server
  _reset_recipe
}

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

teardown(){
  _reset_recipe
  _reset_app

  run $ABRA app secret rm "$TEST_APP_DOMAIN" --all --no-input
}

@test "generate: respect env version" {
  tagHash=$(_get_tag_hash "0.2.0+1.21.0")

  run sed -i 's/TYPE=abra-test-recipe:.*/TYPE=abra-test-recipe:0.2.0+1.21.0/g' \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success

  run $ABRA app secret generate "$TEST_APP_DOMAIN" --all
  assert_success

  assert_equal $(_get_current_hash) "$tagHash"
}

@test "insert: respect env version" { 
  tagHash=$(_get_tag_hash "0.2.0+1.21.0")

  run sed -i 's/TYPE=abra-test-recipe:.*/TYPE=abra-test-recipe:0.2.0+1.21.0/g' \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success

  run $ABRA app secret insert "$TEST_APP_DOMAIN" test_pass_one v1 foo
  assert_success
  assert_output --partial 'successfully stored on server'

  assert_equal $(_get_current_hash) "$tagHash"
}

@test "rm: respect env version" { 
  tagHash=$(_get_tag_hash "0.2.0+1.21.0")

  run sed -i 's/TYPE=abra-test-recipe:.*/TYPE=abra-test-recipe:0.2.0+1.21.0/g' \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success

  run $ABRA app secret generate "$TEST_APP_DOMAIN" --all
  assert_success

  run $ABRA app secret rm "$TEST_APP_DOMAIN" --all
  assert_success

  assert_equal $(_get_current_hash) "$tagHash"
}

@test "ls: respect env version" { 
  tagHash=$(_get_tag_hash "0.2.0+1.21.0")

  run sed -i 's/TYPE=abra-test-recipe:.*/TYPE=abra-test-recipe:0.2.0+1.21.0/g' \
    "$ABRA_DIR/servers/$TEST_SERVER/$TEST_APP_DOMAIN.env"
  assert_success

  run $ABRA app secret generate "$TEST_APP_DOMAIN" --all
  assert_success

  run $ABRA app secret ls "$TEST_APP_DOMAIN"
  assert_success
  assert_output --partial 'true'

  assert_equal $(_get_current_hash) "$tagHash"
}
