
# Install and enable avahi daemon.
#
class avahi::daemon {

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

    if $::operatingsystem == "OpenBSD" {
        service { "dbus-daemon":
            ensure => running,
            enable => true,
            start  => "install -d -o _dbus -g _dbus /var/run/dbus && /usr/local/bin/dbus-daemon --system",
            before => Service["avahi-daemon"],
        }
    }

    service { "avahi-daemon":
        ensure  => running,
        enable  => true,
        status  => "avahi-daemon -c",
        start   => $::operatingsystem ? {
            "openbsd" => "avahi-daemon -D",
            default   => undef,
        },
        require => Package["avahi"],
    }

    file { "/etc/avahi/services":
        ensure  => present,
        purge   => true,
        force   => true,
        recurse => true,
        source  => "puppet:///modules/custom/empty",
        mode    => "0755",
        owner   => "root",
        group   => $::operatingsystem ? {
            "openbsd" => "wheel",
            default   => "root",
        },
        require => Package["avahi"],
    }

}


# Disable avahi daemon.
#
class avahi::disabled {

    service { "avahi-daemon":
        ensure    => stopped,
        enable    => false,
        hasstatus => true,
    }

}


# Modify avahi service.
#
# === Parameters
#
#   $name:
#       Service type. e.g. "_http._tcp".
#   $description:
#       Description of service. Defaults to local hostname.
#   $port:
#       Port which service listens on. Defaults to port found from
#       /etc/services.
#   $txt:
#       Array containing TXT record data.
#   $ensure:
#       If set to present service will be created and if set to absent
#       service will be removed.
#
# === Sample usage
#
# avahi::service { "_ssh._tcp":
#     ensure => present,
# }
#
define avahi::service($port = "AUTO", $description = "%h", $ensure = "present", $txt = []) {

    $filename = regsubst($name, '^_([^.]+)\._.*', '\1.service')

    if $port == "AUTO" {
        $realport = avahi_service_port($name)
    } else {
        $realport = $port
    }

    file { "/etc/avahi/services/${filename}":
        ensure  => $ensure,
        content => template("avahi/service.erb"),
        mode    => "0644",
        owner   => root,
        group   => $::operatingsystem ? {
            "openbsd" => "wheel",
            default   => "root",
        },
        notify  => Service["avahi-daemon"],
    }

}

# Install avahi client support.
#
class avahi::client {

    require avahi::daemon

    package { "avahi-tools":
        ensure => installed,
    }

}
