#!/usr/bin/lua

local unistd = require 'posix.unistd'

if not unistd.access('/etc/opkg/distfeeds.conf') then
	os.exit(0)
end


local site = require 'gluon.site'
local util = require 'gluon.util'


local subst = {}


local f = io.popen('. /etc/os-release; echo "$ID"; echo "$VERSION_ID"; echo "$OPENWRT_BOARD"; echo "$OPENWRT_ARCH"')
subst['%%d'] = f:read()
subst['%%v'] = f:read():gsub('-snapshot', '')
subst['%%S'] = f:read()
subst['%%A'] = f:read()
f:close()

subst['%%GS'] = site.site_code()
subst['%%GV'] = util.trim(util.readfile('/lib/gluon/gluon-version'))
subst['%%GR'] = util.trim(util.readfile('/lib/gluon/release'))

local prefix = subst['%%d'] .. '_'


local function replace_patterns(url)
	for k, v in pairs(subst) do
		url = url:gsub(k, v)
	end

	return url
end


local openwrt = site.opkg.openwrt()
local extra = site.opkg.extra({})


local distfeeds = {}
for line in io.lines('/etc/opkg/distfeeds.conf') do
	table.insert(distfeeds, line)
end

f = io.open('/etc/opkg/distfeeds.conf', 'w')

for _, line in ipairs(distfeeds) do
	local name = line:match('^src/gz%s' .. prefix .. '(%S+)%s')
	if name == 'core' then
		f:write('# ' .. line .. '\n')
	elseif name and openwrt then
		f:write(string.format('src/gz %s %s/%s\n', prefix .. name, replace_patterns(openwrt), name))
	else
		f:write(line .. '\n')
	end
end

f:close()

if next(extra) then
	f = io.open('/etc/opkg/gluon.conf', 'w')

	for k, v in pairs(extra) do
		f:write(string.format('src/gz %s %s\n', k, replace_patterns(v)))
	end

	f:close()

else
	os.remove('/etc/opkg/gluon.conf')
end
