#!/usr/bin/env lua

local home = os.getenv("home") or os.getenv("HOME")
local cache_dir = home .. "/.cache"
local zig_cache = cache_dir .. "/zig"
local proxy_cmd = "ssh -o ProxyCommand='nc -X 5 -x 127.0.0.1:65000 %h %p'"

local project_dir = arg[1] or (home .. "/Projects/river/river")

local function run(cmd)
	local ok = os.execute(cmd)
	if not ok then
		io.stderr:write("failed: " .. cmd .. "\n")
		os.exit(1)
	end
end

local function fetch_git_dep(path, commit)
	local name = path:match("([^/]+)$"):gsub("^zig%-", "")
	local tmp = cache_dir .. "/" .. name .. "-tmp"
	local tarball = cache_dir .. "/" .. name .. ".tar.gz"

	run("rm -rf " .. tmp)
	run('GIT_SSH_COMMAND="' .. proxy_cmd .. '" git clone git@codeberg.org:' .. path .. ".git " .. tmp)
	run("git -C " .. tmp .. " checkout " .. commit)
	run("tar -czf " .. tarball .. " -C " .. cache_dir .. " " .. name .. "-tmp")
	run("zig fetch --global-cache-dir " .. zig_cache .. " file://" .. tarball)
	run(
		"sed -i '/\\."
		.. name
		.. ' = /,/\\.hash/{s|.url = "[^"]*"|.url = "file://'
		.. tarball
		.. "\"|}' "
		.. project_dir
		.. "/build.zig.zon"
	)
end

local function fetch_https_dep(url)
	local filename = url:match("([^/]+)$")
	local name = filename:gsub("^zig%-", ""):gsub("%-v?[0-9].*$", ""):gsub("%.tar%.gz$", "")
	local tarball = cache_dir .. "/" .. filename

	run('GIT_SSH_COMMAND="' .. proxy_cmd .. '" curl -x socks5h://127.0.0.1:65000 -Lo ' .. tarball .. " " .. url)
	run("zig fetch --global-cache-dir " .. zig_cache .. " file://" .. tarball)
	run(
		"sed -i '/\\."
		.. name
		.. ' = /,/\\.hash/{s|.url = "[^"]*"|.url = "file://'
		.. tarball
		.. "\"|}' "
		.. project_dir
		.. "/build.zig.zon"
	)
end

run("git -C " .. project_dir .. " pull")

local zon = io.open(project_dir .. "/build.zig.zon", "r")
if not zon then
	io.stderr:write("cant open build.zig.zon\n")
	os.exit(1)
end

for line in zon:lines() do
	local path, commit = line:match("git%+https://codeberg%.org/([^?]+)%?ref=[^#]+#([a-f0-9]+)")
	if path and commit then
		fetch_git_dep(path, commit)
	else
		local url = line:match('"(https://codeberg%.org/[^"]+%.tar%.gz)"')
		if url then
			fetch_https_dep(url)
		end
	end
end

zon:close()

run("cd " .. project_dir .. " && zig build -Doptimize=ReleaseSafe --prefix " .. home .. "/.local install")
