﻿#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Unpack

import os, sys

completed = []

def unpack(f):
    if os.path.isfile(f):
        cmd = "/usr/bin/unrar e -o+ -kb \"" + f + "\""
        print cmd
        os.system(cmd)
	completed.append(f)

def workDir(directory):
    """ Traverses a directory """
    #print "==============="
    print "Doing directory", directory

    partrarformat = False # file sequences are file.part01.rar, file.part02.rar, etc
    rnullxformat = False # file sequence is file.rar, file.r01, file.r02,
    # find out format (r01 or part01.rar)
    for ff in os.listdir(directory):
        if ff.endswith(".r01"):
            rnullxformat = True
        if ff.endswith("01.rar"):
            partrarformat = True
        #if ff.endswith("part01.rar"):
        #    partrarformat = True
    for f in os.listdir(directory):
        done = False
        if directory[-1] != "/":
            directory += "/"
        #print "f is", os.getcwd() + "/" + directory + f
    
        #handle = os.getcwd() + "/" + directory + f
        handle = directory + f
        #print handle, os.getcwd(), directory
        #print handle
        if os.path.isfile(handle) and not done and f not in completed:
            #print "got a file"
            if (partrarformat and handle.endswith("01.rar")) or (rnullxformat and handle.endswith(".r01")):
                print "Unpack!" , handle
                done = True
                unpack(handle)
        elif os.path.isdir(handle):
            print "traversing", handle
            workDir(handle)
    #print "done" , handle


try:
    p = sys.argv[1]
except IndexError:
    p = ""

# Checking of arguments

if not len(p):
    print "Valid path needed, got", p
    sys.exit(1)

if not os.path.isdir(p):
    print "Valid path needed, got", p
    sys.exit(1)


fullpath = os.getcwd() + "/"


if not p.startswith("/"):
    c = os.getcwd() + "/"
    d = c + p
else:
    d = p
#Do the work...
workDir(p)




# unrar -e : extract to current dir




    
    
