#!/usr/bin/liquidsoap

# Extract timestamp from pige path
def ts_from_filepath (filepath)
	splitpath = string.split(separator='/', filepath)
	# Keep only filename
	filename = list.nth(splitpath,list.length(splitpath)-1)
	int_of_string(list.hd(string.split(separator='\\.', filename)))
end

# Remove pige from now-1month
def  clean_single_old_pige(ts)
	# ts of one month sooner
	ts = ts - 2678400
	filepath = "/soundbase/pige/#{ts}.ogg"
	if file.exists("#{filepath}") then
		process.run("rm #{filepath}")
	end
end

# Remove a pige file if it is too old
def clean_if_old(filename)
	filepath = "/soundbase/pige/#{filename}"
	if ( ts_from_filepath (filename) < int_of_float(time()) - 2678400 ) then
		process.run("rm #{filepath}")
	end
end

# Check that the timestamp starts exactly on a minute
def integrity_check(ts)
	if ts mod 60 != 0 then
		log.important("#{ts} is to fix")
	end
end

# Routine integrity check for each files
def clean_and_check (filepath)
	ts = ts_from_filepath (filepath)
	integrity_check (ts)
	clean_single_old_pige (ts)
end

# Exaustive integrity check
def clean_and_check_all ()
	#list.iter(clean_if_old, file.ls("/soundbase/pige/"))
	list.iter(clean_and_check, file.ls("/soundbase/pige/"))
end



# Mux
input1 = mksafe(input.harbor("direct.ogg",port=8000,password=getenv("ICECAST_SOURCE_PASSWORD")))

# Direct mp3
output.icecast(
  %mp3(bitrate=128, samplerate=22050, stereo=false),
  mount="/direct.mp3",
  host="icecast", port=8000, password=getenv("ICECAST_SOURCE_PASSWORD"),
  input1)

# Radioking
#output.icecast(    
#  %mp3(bitrate=128, samplerate=22050, stereo=false),    
#  mount="/test355",
#  host="live.radioking.com", port=80, user="", password="",
#  input)

# Direct ogg
output.icecast(
  %vorbis(samplerate=44100, channels=1, quality=0.2),
  mount="/direct.ogg",
  host="icecast", port=8000, password=getenv("ICECAST_SOURCE_PASSWORD"),
  input1)

# Pige
output.file(%vorbis(samplerate=44100, channels=1, quality=0.2), {"/soundbase/pige/#{int_of_float(time())}.ogg"}, input1, reopen_when={0s}, reopen_delay=1.0, on_close=clean_and_check)

# Integrity checks
clean_and_check_all()