
local minetest = minetest

local played = 0
local stage = 0

function handle_mus(dtime)
	local tod = minetest.get_timeofday()
	local to_play = nil
	if played < 0 then
		played = 0
	end
	if tod > 0.1917 and tod < 0.1918 then
		-- Sunrise
		if stage == 0 then
			return
		end
		stage = 0
		if played <= 0 and math.random(1, 10) < 50 then
			to_play = {name="www.mathewpablo.com_caketown1", gain=0.9}
			played = 2
		else
			played = played - 1
		end
	elseif tod > 0.75 and tod < 0.76 then
		if stage == 1 then
			return
		end
		stage = 1
		-- Sunset (early)
		if played <= 0 and math.random(1, 10) < 40 then
			to_play = {name="www.mathewpablo.com_snowland", gain=0.9}
			played = 2
		else
			played = played - 1
		end
	elseif tod > 0.7746 and tod < 0.7747 then
		if stage == 2 then
			return
		end
		stage = 2
		-- Sunset
		if played <= 0 and math.random(1, 10) < 30 then
			if math.random(1, 1) == 1 then
				to_play = {name="cynicmusic_crystal_cave_song18", gain=0.9}
			else
				to_play = {name="pauliuw_the_field_of_dreams", gain=0.9}
			end
			played = 2
		else
			played = played - 1
		end
	end
	if to_play == nil then
		return
	end
	for _,player in ipairs(minetest.get_connected_players()) do
		minetest.sound_play(to_play, {
                                to_player = player:get_player_name(),
                                loop = false
                })
	end
end

minetest.register_globalstep(handle_mus)
