#!/usr/bin/lua

local config = require("lime.config")
local fs = require("nixio.fs")

function getopt( arg, options )
  --! Taken from http://lua-users.org/wiki/AlternativeGetOpt
  local tab = {}
  for k, v in ipairs(arg) do
    if string.sub( v, 1, 2) == "--" then
      local x = string.find( v, "=", 1, true )
      if x then tab[ string.sub( v, 3, x-1 ) ] = string.sub( v, x+1 )
      else      tab[ string.sub( v, 3 ) ] = true
      end
    elseif string.sub( v, 1, 1 ) == "-" then
      local y = 2
      local l = string.len(v)
      local jopt
      while ( y <= l ) do
        jopt = string.sub( v, y, y )
        if string.find( options, jopt, 1, true ) then
          if y < l then
            tab[ jopt ] = string.sub( v, y+1 )
            y = l
          else
            tab[ jopt ] = arg[ k + 1 ]
          end
        else
          tab[ jopt ] = true
        end
        y = y + 1
      end
    end
  end
  return tab
end

local lockFilePath = "/var/run/lime-config.pid"
local lockFile = io.open(lockFilePath,"r")
if lockFile then
	lockFile:close()
	print("Cannot acquire lock on "..lockFilePath)
	print("This may be caused by lime-config already running or unexpectedly crashed.")
	print("If it is the latter case (check carefully!) try by deleting the lock file with:")
	print("# rm -rf "..lockFilePath)
	print("Before running lime-config again")
else
	lockFile = io.open(lockFilePath,"w")
	local statFile = io.open("/proc/self/stat", "r")
	lockFile:write(statFile:read("*n"))
	statFile:close()

	opts = getopt( arg, "" )

	config.main()

	--! using --no-commit doesn't guarantee filesystem will not be changed
	--! mainly because many config files are not uci-based
	if not opts["no-commit"] and not opts["n"] then
		local uci = require("uci"):cursor()
		for config,_ in pairs(uci:changes()) do
			uci:commit(config)
		end
	end

	lockFile:close()
	os.remove(lockFilePath)
end
