# @summary Configures a limnoria instance
#
define limnoria::instance (
  String[1] $nickname,
  Hash[Integer, Limnoria::User] $users = {},
  String[1] $directory = $name,
  Array[String[1]] $channels = [],
  Enum['present', 'absent'] $ensure = 'present',
) {
  $instance_dir = "${limnoria::home}/${directory}"
  $directory_ensure = $ensure == 'present' ? {
    true  => 'directory',
    false => 'absent',
  }
  file { $instance_dir:
    ensure  => $directory_ensure,
    mode    => '0750',
    require => Class['limnoria::install'],
  }
  $dirs = ['backup', 'conf', 'data', 'logs', 'plugins']
  $dirs.each | $d | {
    file { "${instance_dir}/${d}":
      ensure  => $directory_ensure,
      mode    => '0750',
      require => File[$instance_dir],
    }
  }

  $instance_vars = {
    'nickname' => $nickname,
    'channels' => $channels,
  }
  file { "${instance_dir}/${name}.conf":
    ensure  => $ensure,
    content => epp('limnoria/instance.conf.epp', $instance_vars),
    require => File[$instance_dir],
    notify  => Service["limnoria-${name}"],
    mode    => '0640',
  }

  $user_vars = {
    'users' => $users,
  }
  file { "${instance_dir}/conf/users.conf":
    ensure  => $ensure,
    content => epp('limnoria/users.conf.epp', $user_vars),
    require => File["${instance_dir}/conf"],
    notify  => Service["limnoria-${name}"],
    mode    => '0644', # Limnoria keeps changing the mode. This shouldn't be
    # world readable though :/
  }

  File <| tag == 'limnoria::instance' |> {
    owner => $limnoria::username,
    group => $limnoria::username,
  }

  $service_vars = {
    'name'               => $name,
    'user'               => $limnoria::username,
    'working_directory'  => $instance_dir,
    'configuration_file' => "${instance_dir}/${name}.conf",
  }
  systemd::unit_file { "limnoria-${name}.service":
    ensure  => $ensure,
    content => epp('limnoria/limnoria.service.epp', $service_vars),
  }

  service { "limnoria-${name}":
    ensure => $ensure == 'present' ? {
      true  => 'running',
      false => 'stopped',
    }
  }

  File["${instance_dir}/${name}.conf"]
  -> File["${instance_dir}/conf/users.conf"]
  -> Systemd::Unit_file["limnoria-${name}.service"]
  -> Service["limnoria-${name}"]
}
