# Install OpenSSL.
#
class ssl::openssl {

    package { "openssl":
        ensure => installed,
    }

}


# Create self-signed certificate.
#
# === Parameters:
#
#   $name:
#       Certificate output file.
#   $cn:
#       Common name.
#   $mode, $owner, $group:
#       Certificate file permissions.
#   $keyout:
#       Key output file. Defaults to ${name}.
#   $keymode, $keyowner, $keygroup:
#       Key file permissions.
#   $days:
#       Validity in days, defaults to 3650.
#   $keysize:
#       RSA key size, defaults to 2048.
#   $subject:
#       Extra subject information.
#
define ssl::certificate($cn, $mode, $owner, $group,
                        $keyout="", $keymode="", $keyowner="", $keygroup="",
                        $days="3650", $keysize="2048", $subject="") {

    include ssl::openssl

    if $keyout {
        $keyout_real = $keyout
        if !$keymode or !$keyowner or !$keygroup {
            fail("\$keymode, \$keyowner and \$keygroup must be defined.")
        }
    } else {
        $keyout_real = $name
    }

    if $subject {
        $subject_real = "/CN=${cn}/${subject}"
    } else {
        $subject_real = "/CN=${cn}"
    }

    exec { "openssl-req-${name}":
        path    => "/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin",
        command => "/bin/sh -c 'umask 077 ; openssl req -x509 -nodes -days ${days} -newkey rsa:${keysize} -subj \"${subject_real}\" -keyout ${keyout_real} -out ${name}'",
        creates => [ "${name}", "${keyout_real}" ],
    }

    file { "${name}":
        ensure  => present,
        mode    => $mode,
        owner   => $owner,
        group   => $group,
        require => Exec["openssl-req-${name}"],
    }

    if $keyout {
        file { "${keyout}":
            ensure  => present,
            mode    => $keymode,
            owner   => $keyowner,
            group   => $keygroup,
            require => Exec["openssl-req-${name}"],
        }
    }

}


# Create DH parameters.
#
# === Parameters:
#
#   $name:
#       Output file.
#   $mode, $owner, $group:
#       Output file permissions.
#   $keysize:
#       Key size. Defaults to 1024.
#
define ssl::dhparam($mode, $owner, $group, $keysize="1024") {

    exec { "openssl-dhparam-${name}":
        path    => "/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin",
        command => "/bin/sh -c 'umask 077 ; openssl dhparam -out ${name} ${keysize}'",
        creates => "${name}",
    }

    file { "${name}":
        ensure  => present,
        mode    => $mode,
        owner   => $owner,
        group   => $group,
        require => Exec["openssl-dhparam-${name}"],
    }

}
