bundle common test_meta
{
  vars:
    "description"
      string => "A user not present gets added with several secondary groups";

    "story_id" string => "5525";
    "covers" string => "operational_repaired";
}

#######################################################
body common control
{
  inputs => {
    "../../default.sub.cf",
    "user_queries.cf.sub",
    "disable_sudo_tty_requirement.cf.sub",
  };
  bundlesequence => { default("$(this.promise_filename)") };
}

#######################################################
body perms init_perms_body_bin
{
  groups => { "$(user_tests.group1)" };
  mode => "664";
}

body perms init_perms_body_sys
{
  groups => { "$(user_tests.group2)" };
  mode => "664";
}

bundle agent init
{
  # Remove him first, should he already be present.
  users:
    "johndoe" policy => "absent";

  files:
    "$(G.testfile)"
      create => "true",
      perms => init_perms_body_bin;

    "$(G.testfile).2"
      create => "true",
      perms => init_perms_body_sys;

  methods:
    "any" usebundle => disable_sudo_tty_requirement;
}

#######################################################
body contain test_contain_body
{
  useshell => "useshell";
}

bundle agent test
{
  users:
    "johndoe"
      policy => "present",
      groups_secondary => { "$(user_tests.group1)", "$(user_tests.group2)" };

  commands:
    sudo_works::
      "sudo -u johndoe /bin/sh -c '$(G.echo) Succeeded > $(G.testfile)'"
        contain => test_contain_body;

      "sudo -u johndoe /bin/sh -c '$(G.echo) Succeeded > $(G.testfile).2'"
        contain => test_contain_body;
}

#######################################################
bundle agent check
{
  methods:
    "any"
      usebundle => user_is_in_secondary_group(
        "johndoe", "$(user_tests.group1)", "bin_success", "bin_failure"
      ),
      classes => always("bin_methods_run");

    "any"
      usebundle => user_is_in_secondary_group(
        "johndoe", "$(user_tests.group2)", "sys_success", "sys_failure"
      ),
      classes => always("sys_methods_run");

  classes:
    !windows::
      "1_ok"
        not => strcmp("0", countlinesmatching("Succeeded", "$(G.testfile)"));

      "2_ok"
        not => strcmp("0", countlinesmatching("Succeeded", "$(G.testfile).2"));

  classes:
    "ready" and => { "bin_methods_run", "sys_methods_run" };

    sudo_works::
      "ok"
        and => {
          "bin_success",
          "!bin_failure",
          "sys_success",
          "!sys_failure",
          "1_ok",
          "2_ok",
        };

    !sudo_works::
      "ok"
        and => { "bin_success", "!bin_failure", "sys_success", "!sys_failure" };

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

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