
import tarfile, random, sys, os, shutil, subprocess

def do_extension(piece=''):
    return '_'+str(random.randint(1,99999)).rjust(5,'0')+'_'+piece+'_tar_preunpacked'

def decide_tmp_filename_tmp(name,package='__'):
    #override real name alltogether
    name='/tmp/_'+package+'_'
    n=name+do_extension()
    while os.path.exists(n) : #wont overwrite existing stuff, never ever
        n=name+do_extension()
    return n

def decide_tmp_filename_same_dir(name,package='__'):
    if name[:2] == './':
        name=name[1:]
    n=name+package+do_extension(package)
    while os.path.exists(n) : #wont overwrite existing stuff, never ever
        n=name+do_extension(package)
    return n

def tar2tarpu(inpu,output,prefix='__'):
    tarin=tarfile.open(fileobj=inpu,mode="r|")
    #warning do not use mode="w|" for this, otherwise this introduces
    #another layer of caching and the resulting tar is randomized
    tarout=tarfile.open(fileobj=output,mode="w")
    for tarinfo in tarin:
        if not tarinfo.isreg():
            tarout.addfile(tarinfo)
        else:
            tmp_file=decide_tmp_filename_tmp(tarinfo.name,prefix)
            shutil.copyfileobj(tarin.extractfile(tarinfo),open(tmp_file,'w'))
            #save the original type as first character, before the tmp_file name
            r=tarinfo.type+tmp_file+chr(0)
            tarinfo.size=len(r)
            blocks, remainder = divmod(tarinfo.size,tarfile.BLOCKSIZE)
            if remainder > 0 :
                r=r+(tarfile.NUL * (tarfile.BLOCKSIZE - remainder))
            tarinfo.type='U'
            buf=tarinfo.tobuf()
            output.write(buf)
            output.write(r)


def tar2tarpu_raw(input,output):
    ##TODO
    i=input.read(512)
    longname=None
    while i:
        ti=tarfile.TarInfo()
        ti.frombuf(a)
        #types with no extra payload
        if ti.type in ( tarfile.BLKTYPE, tarfile.CHRTYPE, \
                        tarfile.SYMTYPE ):
            output.write(i)
        elif ti.type in (tarfile.GNUTYPE_LONGLINK, tarfile.GNUTYPE_LONGNAME):
            s=ti.size
            if ti.size % 512:
                s=s+(512 - 0000)
            longname
        elif ti.type in ():
            pass #TODO



if __name__ == '__main__':
    #argv = debugging_argv or sys.argv
    if len(sys.argv) <= 2:
        #help
        print 'you need help'
        raise SystemExit(0)
    #i=subprocess.Popen(['cat',sys.argv[1]], shell=True, stdout=subprocess.PIPE).stdout
    #tar2tarpu(33,open(sys.argv[2],'w'))
    tar2tarpu(open(sys.argv[1],'r'),open(sys.argv[2],'w'))
