# The ldap-group-maint service.
#
# The ldap-group-maint service looks to see if the groups branch
# (cn=groups,dc=stanford,dc=edu) has changed or if one of the entries in
# the people branch (cn=people,dc=stanford,dc=edu) has an suPrivilegeGroup
# attribute added or removed. In either case, the service will synchronize
# that group's information between these two trees.
#
# See also https://ikiwiki.stanford.edu/service/ldap/sync-scripts/
#
# $generate_gid = 1 means ???. Used in the template files.
#
# $ensure: set to 'present' to run this service on this server, 'absent'
#   to make sure that it does _not_ run.
class su_ldap::sync_scripts::ldap_group_maint (
  $ensure = undef,
  $env = undef,
  $ldap_master_fqdn = undef,
  $generate_gid = 1,    
){

  # Do we want the service to be running or stopped?
  if ($ensure == 'present') {
    $service_status = 'running'
  } elsif ($ensure == 'absent') {
    $service_status = 'stopped'
  } else {
    fail("ensure must be one 'present' or 'absent'")
  }

  #include s_ldap::base::ldap_admin

  # $lsdb_host is used in the template files below.
  case $env {
    prod: {
      $lsdb_host = 'lsdb.stanford.edu'
    }
    'pre', 'sbx', 'wlu', 'dev', 'test', 'uat': {
      $lsdb_host = 'lsdb-test.stanford.edu'
    }
    default: {
      fail("unrecognized environment ${env}")
    }
  }

  ## Configuration files: one for the cron and one for the listener.
  file {
    '/etc/ldapadmin/ldap-group-maint.conf':
      ensure => present,
      content => template('su_ldap/etc/ldapadmin/ldap-group-maint.conf.erb'),
      require => File['/etc/ldapadmin'];
    '/etc/ldapadmin/ldap-group-maint-daemon.conf':
      ensure => present,
      content => template('su_ldap/etc/ldapadmin/ldap-group-maint-daemon.conf.erb'),
      require => File['/etc/ldapadmin'];
  }

  ## Cron job
  file { '/etc/cron.d/ldap-group-maint':
    ensure  => $ensure,
    mode    => '0644',
    source  => 'puppet:///modules/su_ldap/etc/cron.d/ldap-group-maint',
    require => File['/etc/ldapadmin/ldap-group-maint.conf'],
  }


  # We want to reload the systemd daemon on any change to the unit
  # file. We use the base::systemd shared library's systemd-daemon-reload
  # to do this.
  file { '/lib/systemd/system/ldap-group-maint.service':
    ensure => present,
    content => template('su_ldap/lib/systemd/system/ldap-group-maint.service'),
    mode   => '0644',
    notify => Exec['systemd-daemon-reload'],
  }

  service { 'ldap-group-maint':
    ensure  => $service_status,
    require => [
      File['/lib/systemd/system/ldap-group-maint.service'],
      File['/etc/ldapadmin/ldap-group-maint-daemon.conf'],
    ],
  }

}