#!/usr/bin/env python

import glob
import os
import re
import shutil
import subprocess
import sys
import urllib2

import mad


URL_SOURCE = "http://echo.msk.ru/sounds/news.html"
LENGTH_LIMIT = 300


def is_too_long(filename):
    len = mad.MadFile(filename).total_time() / 1000
    print "Duration of %s is %u" % (filename, len)
    return len > LENGTH_LIMIT


def truncate(filename):
    if os.path.exists(filename):
        os.unlink(filename)
        open(filename, "wb").close()


def fetch_news(folder, target, track_id):
    have_news = False

    truncate(target)

    page = urllib2.urlopen(URL_SOURCE).read()
    for url in re.findall("http://.+\.mp3", page):
        if not url.endswith(".mp3"):
            continue
        episode_name = url.split("/")[-1]
        episode_file = os.path.join(folder, episode_name)
        if not os.path.exists(episode_file):
            print "Downloading %s" % url
            data = urllib2.urlopen(url).read()
            file(episode_file, "wb").write(data)
            have_news = True

    if not have_news:
        return

    files = glob.glob(os.path.join(folder, "*.mp3"))
    if not files:
        if os.path.exists(target):
            os.unlink(target)
        print "No news."
        return

    last_file = sorted(files)[-1]

    if is_too_long(last_file):
        if os.path.exists(target):
            os.unlink(target)
        print "Last file too long."
        return

    temp_file = last_file + ".ogg"
    file(temp_file, "wb").write(file(last_file, "rb").read())

    subprocess.Popen(["nice", "-n15", "sox", last_file, "-r", "44100", "-c", "2", temp_file]).wait()
    subprocess.Popen(["nice", "-n15", "vorbisgain", "-q", temp_file]).wait()

    if os.path.exists(target):
        os.unlink(target)
    shutil.move(temp_file, target)

    subprocess.Popen(["ardj", "update-track-lengths", str(track_id)]).wait()


if __name__ == "__main__":
    if len(sys.argv) != 4:
        print >> sys.stderr, "Usage: %s cache_folder target_file track_id" % sys.argv[0]
        exit(1)

    if not sys.argv[2].endswith(".ogg"):
        print >> sys.stderr, "Target file must be OGG/Vorbis."
        exit(1)

    fetch_news(sys.argv[1], sys.argv[2], sys.argv[3])
