#!/usr/bin/env bash

assert() {
  actual="$($1)"
  actual="${actual%$'\n'}"
  expected="${2%$'\n'}"
  if [[ "$actual" != "$expected" ]]; then
    echo "assertion failed, expected '$expected', got '$actual'"
    exit 1
  fi
}
assert_raises() {
  if ! $1; then
    echo "assertion failed: $1"
    exit 1
  fi
}

export RTX_MISSING_RUNTIME_BEHAVIOR=autoinstall

assert_raises "rtx uninstall shfmt@3.6.0"

assert "rtx local" "#:schema ../../schema/rtx.json
env_file = '.test-env'
env_path = [\"/root\", \"./cwd\"]
[env]
FOO = \"bar\"

[tools]
tiny = \"latest\"
#golang = {version=\"1.19.5\", foo=\"bar\"}

[plugins]
tiny-ref = \"https://github.com/rtx-plugins/rtx-tiny#df03b6719dd465d565bb66273942c8495673eaa4\"
"

rtx local shfmt@3.5.0
assert "rtx local" "#:schema ../../schema/rtx.json
env_file = '.test-env'
env_path = [\"/root\", \"./cwd\"]
[env]
FOO = \"bar\"

[tools]
tiny = \"latest\"
shfmt = \"3.5.0\"
#golang = {version=\"1.19.5\", foo=\"bar\"}

[plugins]
tiny-ref = \"https://github.com/rtx-plugins/rtx-tiny#df03b6719dd465d565bb66273942c8495673eaa4\"
"

rtx exec -- shfmt --version >&2
if [[ "$(rtx exec -- shfmt --version)" != "v3.5.0" ]]; then
  exit 1
fi

assert_raises "rtx uninstall shfmt@3.6.0"
assert_raises "rtx local shfmt --install-missing"

rtx local shfmt@3.6.0
assert "rtx local" "#:schema ../../schema/rtx.json
env_file = '.test-env'
env_path = [\"/root\", \"./cwd\"]
[env]
FOO = \"bar\"

[tools]
tiny = \"latest\"
shfmt = \"3.6.0\"
#golang = {version=\"1.19.5\", foo=\"bar\"}

[plugins]
tiny-ref = \"https://github.com/rtx-plugins/rtx-tiny#df03b6719dd465d565bb66273942c8495673eaa4\"
"

rtx exec -- shfmt --version >&2
if [[ "$(rtx exec -- shfmt --version)" != "v3.6.0" ]]; then
  exit 1
fi

rtx local --rm shfmt
assert "rtx local" "#:schema ../../schema/rtx.json
env_file = '.test-env'
env_path = [\"/root\", \"./cwd\"]
[env]
FOO = \"bar\"

[tools]
tiny = \"latest\"
#golang = {version=\"1.19.5\", foo=\"bar\"}

[plugins]
tiny-ref = \"https://github.com/rtx-plugins/rtx-tiny#df03b6719dd465d565bb66273942c8495673eaa4\"
"


export RTX_DEFAULT_CONFIG_FILENAME=.MISSING

assert_raises "rtx uninstall shfmt@3.6.0"

rtx local --install-missing
assert "rtx local" "#python 3.11.1 3.10.9 # foo
shellcheck sub-0.1:0.10.0
shfmt      3.6.0 # test comment
#node    20.0.0
"

rtx local shfmt@3.5.0
assert "rtx local" "#python 3.11.1 3.10.9 # foo
shellcheck sub-0.1:0.10.0
shfmt      3.5.0 # test comment
#node    20.0.0
"

rtx exec -- shfmt --version >&2
if [[ "$(rtx exec -- shfmt --version)" != "v3.5.0" ]]; then
  exit 1
fi

rtx local shfmt@3.6.0
assert "rtx local" "#python 3.11.1 3.10.9 # foo
shellcheck sub-0.1:0.10.0
shfmt      3.6.0 # test comment
#node    20.0.0
"

rtx exec -- shfmt --version >&2
if [[ "$(rtx exec -- shfmt --version)" != "v3.6.0" ]]; then
  exit 1
fi
