##############################################################################
#
#  Test that expireafter works with custom promise types.
#
##############################################################################
body common control
{
  inputs => { "../default.sub.cf" };
  bundlesequence => { default("$(this.promise_filename)") };
  version => "1.0";
}

bundle common version_check
{
  classes:
    "compatible_python_version"
      expression => returnszero(
        "/usr/bin/python3 -c 'import sys; assert sys.version_info >= (3,6)'",
        "useshell"
      );
@if minimum_version(3.22)
    "supports_expireafter" expression => "any";
@endif
}

##############################################################################
bundle agent init
{
  files:
    "$(this.promise_dirname)/cfengine.py"
      copy_from => local_cp(
        "$(this.promise_dirname)/../../../modules/promises/cfengine.py"
      );

    "$(G.testfile)" delete => tidy;
}

##############################################################################
body action background
{
  background => "true";
}

bundle agent test
{
  meta:
    "description" -> { "CFE-3435" }
      string => "Test that expireafter works with custom promise types";

    "test_flakey_fail"
      string => "aarch64.debian_11",
      meta => { "ENT-10623" };

    "test_skip_unsupported"
      string => "!supports_expireafter|!compatible_python_version";

  commands:
    # Note: This sub agent run has to be "identical" to the next
    # sub agent run, so the slow_append promise inside of it
    # will have the same promise hash, and thus expireafter will
    # work.
    "$(sys.cf_agent) --inform --file $(this.promise_filename).sub"
      action => background,
      comment => "I will get killed by the second agent",
      handle => "unique"; # Handle makes the promise lock unique.
    "/bin/sleep 90" comment => "I will wait for the first agent to expire";

    "$(sys.cf_agent) --inform --file $(this.promise_filename).sub"
      comment => "I will kill the first agent";
}

##############################################################################
bundle agent check
{
  vars:
    # Note: Here, the conclusion is a bit fuzzy
    # since both agent runs print this, we don't
    # know for sure exactly what happened.
    # We know that if it's printed once, that looks
    # correct, and if it's printed twice, or 0 times,
    # it's definitely wrong.
    "expected" string => "Hello CFEngine!";

    "actual"
      string => readfile("$(G.testfile)"),
      if => fileexists("$(G.testfile)");

  classes:
    "ok" expression => strcmp("$(expected)", "$(actual)");

  reports:
    ok::
      "$(this.promise_filename) Pass";

    !ok::
      "$(this.promise_filename) FAIL";

    DEBUG::
      "Expected '$(expected)', found '$(actual)'";
}
