#!/usr/bin/luajit

local ffi = require("ffi")

-- lib/ is found beside this script's REAL location (an installed
-- /usr/bin/gpkg is a symlink into the store), never the current
-- directory. Unprivileged, so no ownership checks (syspkg/gstore have
-- those).
ffi.cdef[[
char *gpkg_realpath(const char *path, char *resolved) asm("realpath");
]]
local self_dir
do
        local buf = ffi.new("char[4096]")
        if ffi.C.gpkg_realpath(arg[0], buf) == nil then
                io.stderr:write("gpkg: cannot resolve own location\n")
                os.exit(1)
        end
        self_dir = ffi.string(buf):match("^(.*)/[^/]*$")
        if not self_dir or self_dir == "" then self_dir = "/" end
end
package.path = self_dir .. "/?.lua"
package.cpath = ""

local cargs = require("lib/cargs")
local color = require("lib/color")

local glacier_cdef = require("lib/glacier_cdef")
local common = require("lib/gpkg_common")

-- gpkg is a PER-USER tool only. It deliberately never constructs a
-- GL_SCOPE_SYS context anywhere in this file -- that capability lives
-- exclusively in syspkg. See SECURITY_DESIGN.txt section 5.
local so_dir = self_dir .. "/lib/glacier"
local log = ffi.load(so_dir .. "/libglacier_log.so")
local istore = ffi.load(so_dir .. "/libglacier_istoreutils.so")
local txn = ffi.load(so_dir .. "/libglacier_transaction.so")
local verify = ffi.load(so_dir .. "/libglacier_verify.so")

local txn_name = glacier_cdef.txn_name

local function get_loginuid()
        local f = io.open("/proc/self/loginuid", "r")
        if f then
                local raw = f:read("*l")
                f:close()
                local n = tonumber(raw)
                if n and n ~= 4294967295 then
                        return n
                end
        end
        return tonumber(ffi.C.getuid())
end
local argc, argv = cargs.get_argv()
local args = {}

local longopts = {
	help = "-h",
	version = "-v",
	merge = "-f",
	["local"] = "-l",
	update = "-u",
	remove = "-x",
	refresh = "-y",
	verbose = "-V",
	quiet = "-q",
        ["skip-installed"] = "-S",
        overwrite = "-O",
}

for i = 1, argc - 1 do
	table.insert(args, ffi.string(argv[i]))
end

if #args == 0 then
	log.lg_printf(2, "usage: %s [-hv] [-y] [-flux PKG] [-OSVq]", argv[0])
	os.exit(1)
end

local mode
local pkgs = {}

local isVerbose = false
local skipInstalled = false

-- Wire the shared module up now that log/istore/txn and argv exist.
common.init({ log = log, istore = istore, txn = txn, verify = verify, argv = argv,
        so_dir = so_dir })

-- Why a user's /glacier/usr/<uid> is unusable, before any transaction
-- starts (and before any prompt). Mirrors gl_usr_base_status_t.
local function require_user_dirs(uidn)
        local base = "/glacier/usr/" .. tostring(uidn)
        local st = tonumber(istore.gl_usr_base_status(uidn))
        if st == 1 then
                log.lg_printf(2, "No Glacier directories for UID %s. Run doas gstore -n first.", tostring(uidn))
        elseif st == 2 then
                log.lg_printf(2, "Refusing to run: /glacier/usr is not root-owned, or is group/world-writable.")
        elseif st == 3 then
                log.lg_printf(2, "Refusing to run: %s is not a directory owned by UID %s with mode 0700.",
                        base, tostring(uidn))
        end
        if st ~= 0 then os.exit(1) end

        if not istore.gl_usr_istore_exists(ffi.C.INDEX, uidn)
                        or not istore.gl_usr_istore_exists(ffi.C.STORE, uidn) then
                log.lg_printf(2, "%s is incomplete (no index or store). Ask an administrator to recreate it.", base)
                os.exit(1)
        end
end

local function handle_flag(flag, i)
	if flag == "-h" then
		log.lg_gpkg_help(argc, argv)
	elseif flag == "-v" then
		print("v4.0.0")
	elseif flag == "-V" then
		isVerbose = true
		common.set_verbose(true)
		log.lg_printf(0, "This option enables verbose logging.")
        elseif flag == "-q" then
                common.set_quiet(true)
        elseif flag == "-O" then
                common.set_overwrite(true)
        elseif flag == "-S" then
                skipInstalled = true
                common.set_skip_installed(true)
                if isVerbose then
                        log.lg_printf(0, "Skipping already installed packages.")
                end
	elseif flag == "-f" or flag == "-u" then
                local uidn = get_loginuid()

                if uidn < 1000 then
                        log.lg_printf(2, "Cannot run %s as a system account.", argv[0])
                        os.exit(1)
                end

                local names = {}
                local j = i + 1

                while j <= #args do
                        local arg = args[j]
                        if arg:sub(1, 1) == "-" then break end
                        table.insert(names, arg)
                        j = j + 1
                end

                if flag == "-f" and #names == 0 then
                        log.lg_printf(2, "usage: %s -f PKG...", argv[0])
                        os.exit(1)
                end

                require_user_dirs(uidn)

                local opts = {
                        scope = ffi.C.GL_SCOPE_USR,
                        uid = uidn,
                        scope_label = string.format("for UID %d", uidn),
                }
                if flag == "-f" then
                        common.fetch(names, opts)
                else
                        common.upgrade(names, opts)
                end
	elseif flag == "-l" then
                local uidn = get_loginuid()

		if uidn < 1000 then
			log.lg_printf(2, "Cannot run %s as a system account.", argv[0])
			os.exit(1)
                end

                local gpkg_paths = {}
                local j = i + 1

                while j <= #args do
                        local arg = args[j]
                        if arg:sub(1, 1) == "-" then break end
                        table.insert(gpkg_paths, arg)
                        j = j + 1
                end

                if #gpkg_paths == 0 then
                        log.lg_printf(2, "usage: %s -l PKG...", argv[0])
                        os.exit(1)
                end

		require_user_dirs(uidn)

                common.install(gpkg_paths, {
                        scope = ffi.C.GL_SCOPE_USR,
                        uid = uidn,
                        scope_label = string.format("for UID %d", uidn),
                })
	elseif flag == "-y" then
                local uidn = get_loginuid()

                if uidn < 1000 then
                        log.lg_printf(2, "Cannot run %s as a system account.", argv[0])
                        os.exit(1)
                end
                if args[i + 1] and args[i + 1]:sub(1, 1) ~= "-" then
                        log.lg_printf(2, "-y takes no arguments.")
                        os.exit(1)
                end

                require_user_dirs(uidn)

                os.exit(common.refresh({
                        scope = ffi.C.GL_SCOPE_USR,
                        uid = uidn,
                        scope_label = string.format("for UID %d", uidn),
                }) and 0 or 1)
	elseif flag == "-x" then
                local uidn = get_loginuid()

                if uidn < 1000 then
                        log.lg_printf(2, "Cannot run %s as a system account.", argv[0])
                        os.exit(1)
                end

                local pkg_names = {}
                local j = i + 1

                while j <= #args do
                        local arg = args[j]
                        if arg:sub(1, 1) == "-" then break end
                        table.insert(pkg_names, arg)
                        j = j + 1
                end

                if #pkg_names == 0 then
                        log.lg_printf(2, "usage: %s -x PKG...", argv[0])
                        os.exit(1)
                end

                require_user_dirs(uidn)

                common.remove(pkg_names, {
                        scope = ffi.C.GL_SCOPE_USR,
                        uid = uidn,
                        scope_label = string.format("for UID %d", uidn),
                })
	else
		log.lg_printf(2, "Unknown option: %s", flag)
		log.lg_printf(2, "usage: %s [-hv] [-y] [-flux PKG] [-OSVq]", argv[0])
		os.exit(1)
	end
end

-- Modifier flags change how an action runs but aren't actions. They are
-- applied in a pre-pass so their position doesn't matter: -l acts (and
-- exits) as soon as it's parsed, so without this `-lO` never saw its O
-- and only `-Ol` worked.
local MODIFIERS = { ["-O"] = true, ["-S"] = true, ["-V"] = true, ["-q"] = true }

for idx, raw in ipairs(args) do
	local a = raw
	if a:sub(1, 2) == "--" then
		a = longopts[a:sub(3)] or a
	end
	if a:sub(1, 1) == "-" and a:sub(2, 2) ~= "-" then
		for c in a:sub(2):gmatch(".") do
			if MODIFIERS["-" .. c] then
				handle_flag("-" .. c, idx)
			end
		end
	end
end

local i = 1
while i <= #args do
	local a = args[i]

	-- long option conversion
	if a:sub(1, 2) == "--" then
		local name = a:sub(3)
		local short = longopts[name]
		if not short then
			log.lg_printf(2, "Unknown option: %s", a)
			log.lg_printf(2, "usage: %s [-hv] [-y] [-flux PKG] [-OSVq]", argv[0])
			os.exit(1)
		end
		a = short
	end

	-- grouped flags: -fV, -uxV, etc.
	if a:sub(1, 1) == "-" and #a > 2 and a:sub(2, 2) ~= "-" then
		for c in a:sub(2):gmatch(".") do
			if not MODIFIERS["-" .. c] then
				handle_flag("-" .. c, i)
			end
		end

		-- single flag: -f, -V, -u, etc.
	elseif a:sub(1, 1) == "-" then
		if not MODIFIERS[a] then
			handle_flag(a, i)
		end
	else
		log.lg_printf(2, "Unknown option: %s", a)
		os.exit(1)
	end

	i = i + 1
end
