local function find(args)
	local cmd = string.format('find . -maxdepth 1 %s -printf "%%f\\0"', args)
	local ls = io.popen(cmd, 'r')
	local v = ls:read 'a'
	ls:close()
	local names = {}
	for n in v:gmatch '([^\0]+)' do
		table.insert(names, n)
	end
	return names
end

local polyfx = find '-name "*.n.csd"'
local fx = find '-name "*.csd" -not -name "*.n.csd"'


local function envarg(n, default)
	local v = os.getenv(n)
	if v then return tonumber(v) end
	return default
end

local baseSeed = envarg('starlit_sfx_vary', 420691917)
local variants = envarg('starlit_sfx_variants', 4)
local fmt = os.getenv 'starlit_sfx_fmt' or 'wav'

local rules = {}
local all = {}
if fmt ~= 'ogg' then table.insert(rules,
	'out/starlit-%.ogg: %.' .. fmt .. '\n' ..
		'\tffmpeg -y -i "$<" "$@"\n')
end
local function rule(out, file, seed)
	if fmt == 'ogg' then
		table.insert(rules, string.format(
			'out/starlit-%s.ogg: %s.csd digital.orc physical.orc psi.orc dqual.inc\n' ..
			'\tcsound --omacro:seed=%d --format=ogg -o "$@" "$<"\n',
			out, file,
			seed
		))
	else
		table.insert(rules, string.format(
			'%s.%s: %s.csd digital.orc physical.orc psi.orc dqual.inc\n' ..
			'\tcsound --omacro:seed=%d --format=%s -o "$@" "$<"\n',
			out, fmt, file,
			seed, fmt
		))
	end
	table.insert(all, string.format('out/starlit-%s.ogg', out))
end
for _, v in ipairs(polyfx) do
	local bn = v:match '^(.+).n.csd$'
	for i=1, variants do
		rule(bn .. '.' .. tostring(i), bn .. '.n', baseSeed + 4096*i)
	end
end
for _, v in ipairs(fx) do
	local bn = v:match '^(.+).csd$'
	rule(bn, bn, baseSeed)
end

local makefile = io.open('makefile', 'w')
makefile:write('all: ', table.concat(all, ' '), '\n')
makefile:write('clean:\n\trm ', '"'..table.concat(all, '" "') .. '"', '\n\n')

makefile:write(table.concat(rules, '\n'))
makefile:close()
