#!/usr/bin/env python
# encoding: utf-8

import re, os, getopt, sys
from getopt import (getopt, error)
import scriptutil as SU

toolName = sys.argv[0].split("/")[-1].strip()
help_message = '''
%s: a tool to rename a set of numbered files so that they
are 10 "slots" apart.

%s [-n] [-p path] [-v]

    -c cmd  | --cmd cmd   : rename command to use (default: 'mv')
    -n      | --noaction  : no action, just show what would be done
    -p path | --path path : path where the files reside
    -v      | --verbose   : verbose output
''' % (toolName, toolName)

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):
    verbose = noaction = False
    nfpath = '.'
    rcmd = 'mv'
    # command line arguments handling
    if argv is None: argv = sys.argv
    try:
        # no command line args? print help.
        if not argv[1:]: raise Usage(help_message.lstrip())
        try:
            opts, args = getopt(argv[1:], "hc:p:nv", ["help", "cmd=", "path=",
                                                      "noaction", "verbose"])
        except error, msg: raise Usage(msg)
    
        # option processing
        for option, value in opts:
            if option == "-n": noaction = True
            if option == "-v": verbose = True
            if option in ("-h", "--help"): raise Usage(help_message.lstrip())
            if option in ("-c", "--cmd"): rcmd = value
            if option in ("-p", "--path"): nfpath = value
    except Usage, err:
        print >> sys.stderr, str(err.msg)
        print >> sys.stderr, "For help use --help"
        return 2

    # template of command to run in order to rename/resequence a numbered file
    template = "%s %%s %%s%%03d-%%s" % rcmd
    # regex for finding and taking apart a numbered file (path)
    numberedf = re.compile('^(.+/)(?:\d{3}-)?([^/]+)$')
    # ignore all subversion internal files
    ignore_svn = lambda s: '.svn' not in s

    # get the list of files and sort it
    files = sorted(SU.ffind(nfpath, namefs=(ignore_svn, numberedf.search)))

    # iterate over all files found
    for fidx, f in enumerate(files):
        m = numberedf.match(f)
        if m:
            # found a numbered file, compute its (potentially) new name
            nfn = "%s%03d-%s" % (m.group(1) or '', (fidx+1)*10, m.group(2))
            if f != nfn:    # current and new names different?
                # yes, build the command string for the file at hand
                cmd = template % (f, m.group(1) or '', (fidx+1)*10, m.group(2))
                if noaction: print(cmd)
                else:
                    if verbose: print("running: '%s'" % cmd)
                    os.system(cmd)
            else:
                if verbose: print("ok: %s" % f)

if __name__ == '__main__':
    main()
