#!/usr/bin/ruby

require "resolv"
require "ipaddr"

@debug = false

def getPid_IP()
    @debugfile.puts "Lockfile Pfad: #{@lock_pfad}" if @debug
    begin
        if File.ftype(@lock_pfad) == "link"
            ipListe = File.readlink(@lock_pfad).split(":+")
            begin
                @ip = IPAddr.new(ipListe[0]).to_s
                @pid = ipListe[1]
            rescue => detail
                print detail.backtrace.join("\n") if @debug
                return false
            end
            @debugfile.puts "Link IP: #{@ip}" if @debug
            @debugfile.puts "Link PID: #{@pid}" if @debug
        end
    rescue Errno::ENOENT
        return false
    end
    return true
end

def checkProcessRunning
    pfad = "/proc/"+@pid+"/cmdline"
    if File.exists?(pfad)
        inhalt = File.read(pfad)
        if (not inhalt.nil? and inhalt.include?(@pattern))
            @debugfile.puts "I'm a #{@pattern} under #{pfad}" if @debug
            return true
        else
            @debugfile.puts "I am no #{@pattern} under #{pfad}" if @debug
            return false
        end
    end
    return false
end

def killprocess
    begin
        @debugfile.puts "Sending TERM to Process #{@pid}" if @debug
        Process.kill("TERM", @pid.to_i)
        sleep 5
        @debugfile.puts "Sending KILL to Process #{@pid}" if @debug
        Process.kill("KILL", @pid.to_i)
    rescue
    end
end

def delLock(pfad)
    @debugfile.puts "Cleaning lockfiles" if @debug
    if File.symlink?(pfad)
        @debugfile.puts "Unlinking lock" if @debug
        File.unlink(pfad)
    end
    parentlock = "#{File.dirname(pfad)}/.parentlock"
    if File.exists?(parentlock)
        @debugfile.puts "Unlinking parentlock" if @debug
        File.unlink(parentlock)
    end
    @debugfile.puts "Cleaning lockfiles done" if @debug
end

begin
    if @debug
        @debugfile = File.open("/tmp/cc_debug_#{Time.now.to_i.to_s}", "a")
    end
    
    lockfile = ARGV[0]
    @debugfile.puts "lockfile: #{lockfile}" if @debug
    if File.symlink?(lockfile) and File.lstat(lockfile).owned?
        @lock_pfad = lockfile
        if @lock_pfad.include?("firefox")
            @pattern = "firefox"
        elsif
            @lock_pfad.include?("thunderbird")
            @pattern = "thunderbird"
        else
            @debugfile.puts "Weder Firefox noch Thunderbird lock file angegeben. Exit" if @debug
            if @debug
                @debugfile.close
            end
            exit 1
        end
        getPid_IP
        if checkProcessRunning
            killprocess
        end
        delLock(@lock_pfad)
    else
        @debugfile.puts "Process UID und File UID passen nicht zusammen. Tue nichts" if @debug
    end
ensure
    if @debug
        @debugfile.close
    end
end

