module Puppet
  newtype(:sysctl) do
    @doc = "Manages the sysctl interface for unix-like systems.
    The sysctl module works primarily by managing the /etc/sysctl.conf
    file, and then by calling the 'sysctl -p' command to apply the state
    of the /etc/sysctl.conf file.
    
    This is a very simple type and only makes use of a few paramaters.
    The type only supports three paramaters, the namevar paramater, name,
    is the dot notation reference to the desired sysctl setting, aka
    'vm.swappiness'.  The value paramater is always a string and is the
    value to pass to the gives sysctl setting.  The sysctl trype is also
    ensurable, so all rules need to have the regular ensure => present
    option set.
    
    A typical rule will look like this:
    
        sysctl {'vm.swappiness':
            ensure => present,
            value => '20',
        }
        
    This rule would ensure that the kernel swappiness setting be set to '20'"

    ensurable

    newparam(:name, :namevar => true) do
      desc "The name of the variable in /proc/sys given in dot notation, eg vm.swappiness"
    end
    newparam(:value) do
      desc "The value to enforce for the sys variable."
    end
  end
end

Puppet::Type.type(:sysctl).provide(:sysctl_linux) do
  desc "Support for managing the linux kernel stack"

  def create
    lines = File.new('/etc/sysctl.conf', 'r').readlines
    done = false
    lines.each_index do |i|
      if lines[i].split('=')[0].strip == @resource[:name]
        lines[i] = "#{@resource[:name]} = #{@resource[:value]}\n"
        done = true
      end
    end
    unless done
      lines << "#{@resource[:name]} = #{@resource[:value]}\n"
    end
    sysfile = File.new('/etc/sysctl.conf', 'w')
    for line in lines
      sysfile.write(line)
    end
    sysfile.close
    `sysctl -p`
  end

  def destroy
    lines = File.new('/etc/sysctl.conf', 'r').readlines
    lines.each_index do |i|
      if lines[i].split('=')[0].strip == @resource[:name]
        lines[i] = ""
    end
    sysfile = File.new('/etc/sysctl.conf', 'w')
    for line in lines
      sysfile.write(line)
    end
    sysfile.close
    `sysctl -p`
  end
  end
    
  def exists?
    lines = File.new('/etc/sysctl.conf', 'r').readlines
    lines.each do |line|
      if line.split('=')[0].strip == @resource[:name]
        if line.split('=')[1].strip == @resource[:value]
          return true
        elsif @resource[:ensure] == :absent
          return true
        end
      end
    end
    return false
  end
end

