# By default we want to run an IMAP(s) server and disabled pop3 + nntp.
#
#   $cyrus_key:
#       Path to SSL private key. Defaults to puppet client key.
#
#   $cyrus_cert:
#       Path to SSL certificate. Defaults to puppet client certificate.
#
#   $cyrus_admins:
#       List of users "user1 user2", which have admin rights on the IMAP server.
class cyrus {

    case $::operatingsystem {
        "ubuntu","debian": {}
        default: {
            fail("cyrus not supported on ${::operatingsystem}")
        }
    }

	include ssl	

    if !$cyrus_key {
        $postfix_key = "${puppet_ssldir}/private_keys/${homename}.pem"
    }

    if !$cyrus_cert {
        $postfix_cert = "${puppet_ssldir}/certs/${homename}.pem"
    }

    if !$cyrus_admins {
        $cyrus_admins = "admin"
    }

    package { [
    	"cyrus-imapd-2.4",
    	"cyrus-clients-2.4",
    	"cyrus-admin-2.4",
    	"cyrus-doc-2.4", ]:
        ensure => present,
    }

    service { "cyrus-imapd":
        ensure  => running,
        enable  => true,
        require => Package["cyrus-imapd-2.4"],
    }

    file { "${ssl::certs}/cyrus.crt":
        ensure  => present,
        source  => $cyrus_cert,
        mode    => "0644",
        owner   => "root",
        group   => "root",
        notify  => Service["cyrus-imapd"],
    }

    file { "${ssl::private}/cyrus.key":
        ensure  => present,
        source  => $cyrus_key,
        mode    => "0640",
        owner   => "root",
        group   => "mail",
        notify  => Service["cyrus-imapd"],
    }
    
    exec { "usermod-cyrus-ssl-cert":
        path    => "/bin:/usr/bin:/sbin:/usr/sbin",
        command => "usermod -a -G ssl-cert cyrus",
        unless  => "id -n -G cyrus | grep '\\bssl-cert\\b'",
        notify  => Service["cyrus-imapd"],
    }

    file { "/etc/cyrus.conf":
        ensure  => present,
        mode    => "0644",
        owner   => "root",
        group   => "root",
        source => "puppet:///modules/cyrus/cyrus.conf",
        notify  => Service["cyrus-imapd"],
        require => Package["cyrus-imapd-2.4"],
    }

    file { "/etc/imapd.conf":
        ensure  => present,
        mode    => "0644",
        owner   => "root",
        group   => "root",
        content => template("cyrus/imapd.conf.erb"),
        notify  => Service["cyrus-imapd"],
        require => Package["cyrus-imapd-2.4"],
    }

    file { "/run/cyrus/socket":
        ensure => directory,
        mode => "0750",
        owner => "cyrus",
        group => "postfix",
    }

    # Fix broken ubuntu packaging
    file { "/run/cyrus/lock":
        ensure => directory,
        mode => "0750",
        owner => "cyrus",
        group => "mail",
    }

    # Fix broken ubuntu packaging
    file { "/run/cyrus/proc":
        ensure => directory,
        mode => "0750",
        owner => "cyrus",
        group => "mail",
    }
}