body file control {
  # To make this policy "standalone" we load parts of the standard library that
  # we use
  inputs => { "$(sys.libdir)/files.cf", "$(sys.libdir)/packages.cf" };
}

bundle agent motd {

  vars:
    "motd_path" string => "/etc/motd";
    "template_path" string => "$(this.promise_filename).mustache";

    ## This is to extract the cf-engine role ( hub or client )
    "cf_role"
      string => ifelse( "policy_server", "Policy Server", "Policy Client");

    ## This is to extract the available package updates status
    "updates_available"
      data => packageupdatesmatching(".*", ".*", ".*", ".*");
    "amount_updates" int => length("updates_available");

    ## This is to define a production / stage example role for the server
    "environment_list" slist => { "/etc/prod", "/etc/staging" };
    "environment"
      string => ifelse( filesexist( @(environment_list) ), "unknown",
                        fileexists("/etc/prod"), "production",
                        fileexists("/etc/staging"), "staging",
                        "unknown" );

    ## Based on the environment we define different contatcs.
    "admin_contact"
      slist => { "admin@acme.com", "oncall@acme.com" },
      if => strcmp( $(environment), "production" );

    "admin_contact"
      slist => { "dev@acme.com" },
      if => strcmp( $(environment), "staging" );

    "admin_contact"
      slist => { "root@localhost" },
      if => strcmp( $(environment), "unknown" );

  ## We define a class to conditionally render the role status in the final
  ## motd.
  classes:
    "env_$(environment)" expression => "any";

  ## In order to get package inventory, we need to have a legacy package
  ## promise.
  packages:
    "vim" -> { "https://dev.cfengine.com/issues/7864" }
      package_policy => "add";

  ## Here is where we render the mustache template
  files:
    "$(motd_path)"
      create => "true",
      perms => mog( 444, "root", "root"),
      template_method => "mustache",
      edit_template => "$(template_path)";

  ## These are good to understand what is going on.
  reports:
    DEBUG|DEBUG_motd::
      "DEBUG $(this.bundle): $(sys.cf_version) is the detected version";
      "DEBUG $(this.bundle): $(sys.fqhost) is the detected hostname";
      "DEBUG $(this.bundle): $(sys.ipv4) is the ipv4 address for $(sys.fqhost)";
      "DEBUG $(this.bundle): $(motd.cf_role) is the detected role";
      "DEBUG $(this.bundle): $(amount_updates) packages can be updated";
      "DEBUG $(this.bundle): This host is managed by $(admin_contact)";
}
