---AwesomeWM autorun system
-- This module provides a way to start up applications on desktop boot
-- It's like cron's @reboot but with additional awesomewm specific features
local awful = require("awful")
local rcfile = io.open(global.config_dir.."rc.lua")
local execute 
-- why thank you lua changes, i appreciate this shit.
-- (luajit is deprecated my ASS, find me a faster version then)
if _VERSION ~= "Lua 5.1" then
    execute = function(comm)
        return select(3,os.execute(comm))
    end
else
    execute = os.execute
end
local execd = {}
-- load persistent file for "o" tag
local execd_file = io.open("/tmp/awesomerc.started","r")
if execd_file then 
    execd_file:read("*a"):gsub("[^\n]+",function(prg)
        execd[prg] = true
    end)
    execd_file:close()
end
execd_file = io.open("/tmp/awesomerc.started","w")
local function check_pid(prg)
    local args = {}
    prg:gsub("[^%s ]+",function(name)
        args[#args+1] = name
    end)
    local prgname
    for _,prgn in pairs(args) do
        if prgn:match("^[^=]+$") then
            prgname = prgn:match("[^/]+$"):sub(1,15)
            break
        end
    end
    if execute("pgrep "..prgname) == 0 then
        return true
    else 
        return false
    end
end
local function check_once(prg)
     if not execd[prg] then
        execd[prg] = true
        execd_file:write(tostring(prg).."\n")
        return true
     end
end
local function apply_tags(k,prg)
    if k:match("n") and (check_pid(prg)) then
        return false
    end
    if k:match("o") and (not check_once(prg)) then
        return false
    end
    awful.spawn(prg)
    return true
end
     
if rcfile then
    local rc,err = load(rcfile:read("*a"))
    rcfile:close()
    local rcdata
    if not err then
        rcdata = rc()
    else
        require("naughty").notify({
            title = "Error reading rc.lua",
            text = err
        })
    end
    for entry,command in pairs(rcdata or {}) do
        apply_tags(entry,command)
    end
end
execd_file:close()
