##############################################################################
#
# Test that agent reports the immutable bit in the error message when it
# cannot render a classic CFEngine template over an immutable file (no
# override).
#
# CFEngine templating writes a temporary file and renames it over the target,
# so the failure surfaces from OverrideImmutableRename(). The whole scenario
# (create template + immutable destination, then fail to render) runs in a
# self-contained sub policy: its setup happens in its own agent process, so it
# does not depend on this test's evaluation order, and its non-zero exit does
# not fail this test. We only assert on the captured error output. Teardown
# clears the immutable bit natively via body fsattrs.
#
##############################################################################
body common control
{
  inputs => { "../../default.sub.cf" };
  bundlesequence => { default("$(this.promise_filename)") };
  version => "1.0";
}

bundle agent global
{
  vars:
    "template" string => "/tmp/18_immutable.cf-template";
    "testfile" string => "/tmp/18_immutable.txt";
}

body fsattrs clear_immutable
{
  immutable => "false";
}

bundle agent test
{
  meta:
    "description" -> { "ENT-14297" }
      string => "Test that a cfengine template render onto an immutable file names the immutable bit in the error";

    "test_skip_unsupported" string => "hpux|aix|solaris|windows";
}

bundle agent check
{
  vars:
    "run"
      data => execresult_as_data(
        "$(sys.cf_agent) -KI -f $(with)", "noshell", "both"
      ),
      with => regex_replace("$(this.promise_filename)", "\.cf$", ".sub.cf", "");

  classes:
    "ok"
      expression => regcmp(
        ".*Failed to replace.*the immutable bit is set.*", "$(run[output])"
      );

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

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

    DEBUG::
      "$(this.bundle): agent exited '$(run[exit_code])', output was:";
      "$(run[output])";
}

bundle agent destroy
{
  files:
    "$(global.testfile)"
      delete => tidy,
      fsattrs => clear_immutable;

    "$(global.testfile).cf-before-edit" delete => tidy;
    "$(global.template)" delete => tidy;
}
