#!/usr/bin/python
import string,os,time,sys

#
# requestsfile = 1 filename per line, first one is the one we are playing
# timestampfile = first line holds unix timestamp (as ASCII integer) of
#                 current OGG file being played

datadir="/tmp/oggradio"
requestsfile=datadir+"/requests"
timestampfile=datadir+"/timestamp"
oggtailpath="/space/streamer/oggtail.py"

def updatetimestamp():
    f=open(timestampfile,"w")
    f.write(str(int(time.time())))
    f.close()

def setup():
    try: os.mkdir(datadir)
    except OSError: pass
    open(requestsfile,"w").close()
    updatetimestamp()

def run():
    requests=open(requestsfile).readlines()
    try:
        song=requests[0].strip()
    except:
        print "Request queue seems to be empty. Exitting"
        raise
    while 1:
        timestamp=int(open(timestampfile).readlines()[0])
        break
    elapsed=time.time()-timestamp
    junk,data=os.popen2('ogginfo "%s"|grep ^length='%song)
    songlength=float(data.read().split("=")[1])
    percent=100.0*elapsed/songlength
    if percent>90:
        # skip to next song
        updatetimestamp()
        f=open(requestsfile,"w")
        f.writelines(requests[1:])
        f.close()
        return
    command='%s --percent=%f "%s"'%(oggtailpath,100-percent,song)
    os.system(command)

def http():
    request=raw_input()
    # GET /... HTTP/*
    url=request.split(" ")[1]
    print "HTTP/1.1 200 OK %s -- ca roule!"%url
    if url=="/":
        print "Content-Type: text/plain"
        print ""
        print "playlist:"
        sys.stdout.flush()
        os.system('cat "%s"'%requestsfile)
        sys.exit()
    print "Content-Type: application/x-ogg-radio-stream-ouhyeah"
    print ""
    sys.stdout.flush()
    
http()
while 1:
    run()
    time.sleep(1)
