# Manage a service using daemontools.
#
# Example using a file resource for the run script:
#
#     base::daemontools::supervise { 'postfix-k5':
#       ensure => present,
#       source => 'puppet:///modules/s_mailman/service/postfix-k5/run',
#     }
#
# Example using a template for the run script and enabling logging:
#
#     base::daemontools::supervise { 'signal':
#       ensure       => present,
#       content      => template('base/s_ldap/signal-run.erb'),
#       logging      => '/var/log/signal',
#       logging_mode => '0755',
#     }

define base::daemontools::supervise(
  $ensure       = 'present',
  $source       = undef,
  $content      = undef,
  $logging      = '',
  $logging_mode = '0750'
) {
  $svcdir = "/service/${name}"
  $run = "/service/${name}/run"

  if ($source == undef) and ($content == undef) and ($ensure == 'present') {
    fail('source or content required')
  }
  if ($source != undef) and ($content != undef) {
    fail('Specify source or content but not both')
  }

  case $ensure {
    # Stop the service.  We have to first move the service directory aside so
    # that svscan doesn't just restart it, then stop the service and the
    # supervise process, and finally delete the directory.
    absent: {
      exec { "remove ${svcdir}":
        command => "mv ${svcdir} /service/.${name} && svc -dx /service/.${name} && (if [ -d /service/.${name}/log ] ; then svc -dx /service/.${name}/log ; fi) && rm -rf /service/.${name}",
        onlyif  => "[ -d ${svcdir} ]",
      }
    }

    # Create the service.
    present: {
      include base::daemontools

      file { $svcdir:
        ensure => directory,
        mode   => $logging ? { '' => '0755', default => '01755' }
      }
      file { $run:
        source  => $source,
        content => $content,
        mode    => '0755',
        notify  => Exec["svc -u ${svcdir}"],
      }

      # Configure logging if desired.
      if $logging != '' {
        file {
          "${svcdir}/log":
            ensure  => directory,
            mode    => 755;
          $logging:
            ensure  => directory,
            mode    => $logging_mode;
          "$svcdir/log/run":
            content => template('base/daemontools/log-run.erb'),
            mode    => '0755';
        }
      }
    }

    # Catch all other ensure options.
    default: {
      fail("Invalid ensure value: ${ensure}")
    }
  }

  # Start the service.
  exec { "svc -u ${svcdir}":
    command     => "svc -u ${svcdir}",
    refreshonly => true,
  }
}