#!/usr/bin/env python
 
# PJB vfs script for Midnight Commander - version 1.0
#  Created in 2001 by Erwin S. Andreasen - http://www.andreasen.org/misc.shtml
#  This program is hereby placed in the Public Domain
#
# 1) Copy this script to /usr/lib/mc/extfs/pjb
# 2) Edit extfs.init, add line "pjb:"
# 3) Start mc, change directory to "#pjb"
#
# To run this program you need the following installed:
#  Python 2.0 (www.python.org)
#  The "pjb" command, *probably* version 3.0-tt1 (this is a patched version with more
#    capabiilities.
#   Unfortunately I don't remember where I got it) )
#
# After a transfer, MC will try to chown the target -- that obviously cannot work. Just
#  press SKIP. Also, the screen is likely to be fubar'ed -- press control-L to refresh it.


# import erwutil as util
import sys, re, os

SetRx = re.compile(r'^Set: (.+)')
DiscRx = re.compile(r'^\s+Disc: (.+)')
TrackRx = re.compile(r'\s+Track: (.+)')
TimeRx = re.compile(r'BitRate=(\d+).*Time=(\d+)')

# Character maps for escaping from PJB's characters to UNIX
EscapeMap = {
    ' ' : '\xA0',
    '/' : '\xA6'
    }
UnescapeMap = {}
for k,v in EscapeMap.items():
    assert not UnescapeMap.has_key(v), "Irreversible escape mapping"
    UnescapeMap[v] = k

def applyMap(s,map):
    if s:
        for k,v in map.items():
            s = s.replace(k,v)
    return s

def escape(s):    return applyMap(s,EscapeMap)
def unescape(s):  return applyMap(s,UnescapeMap)

    

def emitEntry(set,disc,track,size):
    if track is None:
        type = 'd'
    else:
        type = '-'

    disc,set,track = map(escape,[disc,set,track])

    if disc is None:
        name = '%s/' % escape(set)
    elif track is None:
        name = '%s/%s' % (escape(set), escape(disc))
    else:
        name = '%s/%s/%s.mp3' % (set,disc,track)

    print '%srwxrwxrwx %03d %-8s %-8s %08d Jan 01 2001 %s' % (type, 1, 'pjb', 'pjb', size, name)
        
        
              
def doList(args):
    set = None
    disc = None
    track = None
    
    for line in os.popen("pjb ls -all").readlines():
        setM,discM,trackM,timeM = [x.search(line) for x in [SetRx, DiscRx, TrackRx, TimeRx]]
        if setM:
            set = setM.group(1)
            emitEntry(set,None,None,0)
        elif discM:
            disc = discM.group(1)
            emitEntry(set,disc,None,0)
        elif trackM:
            track = trackM.group(1)
        elif timeM:
            bitRate,time = map(int, timeM.group(1,2))
            size = time * (bitRate/1000) * 1.5
            emitEntry(set,disc,track,int(size))
        else:
            continue

def run(command):
    # Start out by clearing the screen
    os.system("tput rmacs;tput clear")
    open('/tmp/log', 'a').write("RUN: %s\n" % command)
    pipe = os.popen(command, 'r', 1)
    print "\r"
    while 1:
        r = pipe.read(1)
        if not r: break
        sys.stdout.write(r.replace('\n','\r\n'))
        sys.stdout.flush()


# We can't mkdir -- we just pjb add with the right -set/-disc
# So we pretend mkdir works all right...
def doMkdir(args):
    pass

def doCopyout(args):
    pass
    

def doCopyin(args):
    archive,stored,source = args
    # archive is ignored (we only have one PJB)
    # stored is the TARGET filename
    # source is the SOURCE filename

    # Ensure that the target has exactly 3 components (set, disc, track)
    try:
        set,disc,track = stored.split('/')
    except ValueError:
        sys.exit(1)

    tempfile= '/tmp/%s' % track
    try:     os.unlink(tempfile)
    except:  pass
    
    os.symlink(source, tempfile)
    set,disc = map(unescape,[set,disc])
    run("pjb add -notags -set='%s' -disc='%s' %s" %(set,disc,tempfile))
    os.unlink(tempfile)


def doRm(args):
    stored = args[1]
    set,disc,track = map(unescape,stored.split('/'))
    track = track.replace('.mp3','')
    run("echo yes|pjb delete -set='%s' -disc='%s' '%s'" % (set,disc,track))

def doRmdir(args):
    # Delete a whole DISC (but don't allow delete of SET)
    set,disc = map(unescape,args[1].split('/'))
    run("yes|pjb delete -set='%s' -disc='%s'" % (set,disc))
    
    

def main():
    if len(sys.argv) < 2:
        print "Not enough args."
        sys.exit(2)
    open('/tmp/log', 'a').write("%r\n" % sys.argv)
    cmd = sys.argv[1]
    fun = globals().get('do%s' % cmd.capitalize())
    if not fun:
        print "Command %s not implemented" % cmd
        sys.exit(1)
    else:
        fun(sys.argv[2:])


if __name__ == '__main__':
    main() #util.run(main)
    
