# Manage OpenBSD services. Enable/disable using /etc/rc.local, /etc/rc.conf.local

Puppet::Type.type(:service).provide :openbsd, :parent => :base do
    desc "OpenBSD service management."

    defaultfor :operatingsystem => [:openbsd]

    @@rclocal = "/etc/rc.local"
    @@rcconf = "/etc/rc.conf"
    @@rcconflocal = "/etc/rc.conf.local"

    def getrcconf
	File.readlines(@@rcconf).each { |line|
	    if line =~ /^#{@resource[:name]}_flags=.*/
		return "#{@resource[:name]}_flags"
	    elsif line =~ /^#{@resource[:name]}=.*/
		return @resource[:name]
	    end
	}
	return false
    end

    def enabled?
	if not defined? @resource[:start]
	    raise Puppet::Error,
		"Services must specify a start command or a binary"
	end
	flag = getrcconf()
	if flag
	    File.readlines(@@rcconflocal).each { |line|
		line = line.strip.split(/=/, 2)
		next unless line[0] == flag
		if line[1] == "NO"
		    return :false
		end
		return :true
	    }
	    return :false
	else
	    inlocal = false
	    File.readlines(@@rclocal).each { |line|
		line = line.strip
		if not inlocal
		    next unless \
			line == "# Add your local startup actions here."
		    inlocal = true
		else
		    if line == "echo '.'"
			inlocal = false
			break
		    end
		    next unless line =~ /^echo -n \" #{@resource[:name]}\" ; .*/
		    return :true
		end
	    }
	    return :false
	end
    end

    def enable
	flag = getrcconf()
	if flag
	    newdata = ""
	    File.readlines(@@rcconflocal).each { |line|
		if line.strip.split(/=/, 2)[0] == flag
		    next
		else
		    newdata += line
		end
	    }
	    if flag == @resource[:name]
		newdata += "%s=YES\n" % flag
	    elsif flag == "#{@resource[:name]}_flags"
		if @resource[:start] != nil and @resource[:binary] != nil
		    args = @resource[:start][/^#{@resource[:binary]} (.*)/, 1]
	        end
		newdata += "%s=\"%s\"\n" % [flag, args]
	    end
	    f = File.open(@@rcconflocal, "w")
	    f.write(newdata)
	    f.close
	else
	    newdata = ""
	    inlocal = false
	    File.readlines(@@rclocal).each { |line|
		if line == "# Add your local startup actions here.\n"
		    newdata += line
		    newdata += "echo -n \" %s\" ; %s\n" % [@resource[:name],
							   @resource[:start]]
		    next
		end
		newdata += line
	    }
	    f = File.open(@@rclocal, "w")
	    f.write(newdata)
	    f.close
	end
	return :true
    end

    def disable
	flag = getrcconf()
        if flag
            newdata = ""
            File.readlines(@@rcconflocal).each { |line|
                if line.strip.split(/=/, 2)[0] == flag
                    next
                else
                    newdata += line
                end
            }
            if flag == @resource[:name] or flag == "#{@resource[:name]}_flags"
                newdata += "%s=NO\n" % flag
            end
            f = File.open(@@rcconflocal, "w")
            f.write(newdata)
            f.close
        else
	    print "disabling services from rc.local not implemented\n"
	end
	return :true
    end

end