#!/usr/bin/env python

"""
   cdmp3 prepare le gravage et produit le LaTeX de couverture

usage: cdmp3.py  -d <repertoires> -o <output path> [-h] 
cdmp3.py -d /var/mp3/fredz/Afro/:/var/mp3/fredz/Funk/:/var/mp3/fredz/Soul/:/var/mp3/fredz/Oldies/ -o /home/fredz/mp3vol
  -h: cette aide
"""

import os
from stat import *
import getopt
import sys
from string import *


# mkisofs -f -J -r -o /var/cdrecord/image.raw /home/fredz/mp3vol/
# 
# cdrecord dev=0,4,0 blank=fast speed=4 driver=mmc_cdr
# cdrecord -v dev=0,4,0  speed=4 driver=mmc_cdr -data /var/cdrecord/image.raw

def usage(*args):
    sys.stdout = sys.stderr
    for msg in args: print msg
    print __doc__
    sys.exit(2)

class MP3_File:
    def __init__(self, num, initpath, file, crunched_file):
        self.num = num
        self.initpath = initpath
        self.file = file
        self.crunched_file = crunched_file
    def __repr__(self): # surcharge pour le print
        return "%s:%s:%s:%s" % (self.num, self.initpath, self.file, self.crunched_file)

class MP3_List:
    def __init__(self):
        self.num = 1
        self.dict = {}
        self.tabletrans = maketrans('\0','\255')
        
    def __repr__(self):
        s = ""
        n = max(self.dict.keys())
        for i in range(1, n+1):
            s = s + "%s : %s\n" % (i, self.dict[i])
        return s

    def crunch_file(self,file):
        return "%.3d%.5s.mp3" % (self.num, translate(file, self.tabletrans, '&_0123456789йилкащ$*-[]() \.\'\n\r'))
    def add(self, path, file):
        mp3_file = MP3_File(self.num, path, file, self.crunch_file(file))
        self.dict[self.num] = mp3_file
        self.num = self.num + 1

    def walktree(self, dir):
        ldir = os.listdir(dir)
        ldir.sort()
        for f in ldir:
            pathname = '%s/%s' % (dir, f)
            mode = os.stat(pathname)[ST_MODE]
            if S_ISDIR(mode):
                self.walktree(pathname) # It's a directory, recurse into it
            elif S_ISREG(mode):
                self.add(pathname, f) # It's a file, call the callback function
            else:
                print 'Skipping %s' % pathname # Unknown file type, print a message
    def write_image(self, destdir):
        n = max(self.dict.keys())
        for i in range(1, n+1):
            mp3_file = self.dict[i]
            os.symlink(mp3_file.initpath, "%s/%s" % (destdir, mp3_file.crunched_file))

    def write_latex(self, destdir):
        print """
\\documentclass[french,11pt]{article} 
\\usepackage[T1]{fontenc}
\\usepackage{times} 
\\usepackage{a4} 
\\usepackage{babel}
\\usepackage{longtable}
\\usepackage{vmargin}
\\setmarginsrb{3cm}{10cm}{2cm}{7cm}{0in}{0in}{0in}{0in}
\\pagestyle{empty}
\\begin{document}
\\begin{tiny}
\\begin{longtable}{|l|p{105mm}|}
\\hline 
{\\bf index} & champ \\endfirsthead
\\hline
{\\bf index} & champ \\\\
\\hline
\\textit{ (suite)} & \\textit{ (suite)}\\endhead
\\multicolumn{2}{|c|}{\\textit{ Suite...}} \\\\ \\hline \\endfoot
%\\endlastfoot
%\\noindent
%\\begin{tabular}{|r|@{}l}
"""
        n = max(self.dict.keys())
        for i in range(1, n+1):
            mp3_file = self.dict[i]
            file = mp3_file.file[:-4]
            file = translate(file, self.tabletrans, '[]')
            antichars = '[]&_'
            for c in antichars:
                file = replace(file,c,'\\%s' % c)
            print "\\hline {\\tt\\bf %s} & %s \\\\" % (upper(mp3_file.crunched_file[:-4]), file)
        print """\\hline
        \\end{longtable}
        \\end{tiny}
        \\end{document}"""

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'd:o:')
    except getopt.error, msg:
        usage(msg)

    spath = outpath = ''
    for o, a in opts:
        if o == '-d': spath = a
        if o == '-o': outpath = a
    if not spath or not outpath:
        usage("missing parameters")

    mp3_list = MP3_List()
    lpath = split(spath,":")
    for path in lpath:
        mp3_list.walktree(path)
    mp3_list.write_image(outpath)
    mp3_list.write_latex(outpath)
if __name__ == '__main__':
	main()

