---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 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 os.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()