#!/bin/lua

-- Mixxx CUE sheet to aNONradio metadata
-- And also text tracklist

local path = arg[1]
local basename = ""

do
 local cur_pos = 1
 for i = 1, path:len() do
   local start_pos, end_pos = path:find("/", cur_pos, true)
   if not start_pos then break end

   cur_pos = end_pos + 1
 end

 basename = path:sub(cur_pos)
end

local cuefile = io.open(path)
if not cuefile then
 print("Failed to read file.")
 os.exit(1)
end

local content = cuefile:read("a")
cuefile:close()

if not content:match('FILE "(.-)" MP3\n') then
 print("Provided file not a CUE sheet")
 os.exit(1)
end

local meta = ""
local plain = "Archive link: https://archives.anonradio.net/" .. basename:gsub("cue","mp3") .. "\n\n"

for track in content:gmatch('%s-TRACK %d- AUDIO\n%s-TITLE ".-"\n%s-PERFORMER ".-"\n%s-INDEX %d- %d-:%d+') do
 local index = track:match("TRACK (%d-) AUDIO")
 local title = track:match('TITLE "(.-)"')
 local artist = track:match('PERFORMER "(.-)"')
 local time = track:match("INDEX %d- (%d-:%d+)"):gsub(":", "")

 if index == "01" then
   time = "0010"
 end

 meta = meta .. "00" .. time .. ":" .. artist .. " - " .. title .. "\n"
 plain = plain .. artist .. " - " .. title .. "\n"
end

local metafile = io.open(basename:gsub("cue", "meta"), "w")
local metasucc = metafile:write(meta)
if not metasucc then
 print("Failed to write meta file.")
else
 metasucc:close()
 print("Wrote meta file.")
end

local plainfile = io.open(basename:gsub("cue", "txt"), "w")
local plainsucc = plainfile:write(plain)
if not plainsucc then
 print("Failed to write tracklist file.")
else
 plainsucc:close()
 print("Wrote tracklist file.")
end