#!/usr/bin/python3
import re, tarfile, sys
from os.path import exists as file_exists
class xcp_restore:

    def __init__(self, backup_name, xva):
        self.backup_name = str(backup_name)
        self.RELATIVE = 1
        self.BLOCK_SIZE = 2**20
        self.xva = xva
        
    def get_filedata(self):
        files = {}
        vps_disk = {}
        for tarinfo in self.xva:
            if (tarinfo.name.split('/')[0]):
                files[(tarinfo.name.split('/')[0])] = str(tarinfo)
                

        for file in files:
            if ('xml' in file): continue
            file_data = re.split(''+file+'/| ', files[file])
            if(file_data[2].split('.')[0]):
                vps_disk[file] = file_data[2].split('.')[0]
        return vps_disk

    def get_block(self, ref, n):
        try:
            file_data = self.xva.extractfile("%s/%08d" % (ref, n)).read()
            return file_data
        except KeyError:
            return None

    def write_file(self, ref, blocks, output):
        try:
            out_file = open(output, 'wb')
            for n in range(0, blocks+1):
                if n % 123 == 0:
                    print('\r', n, end = ''),
                    sys.stdout.flush()
                block = self.get_block(ref, n)
                if block is not None:
                    out_file.write(block)
                else:
                    out_file.seek(self.BLOCK_SIZE, self.RELATIVE)

            print('\r', 'Done.')
            out_file.close()
            return True
        except IOError:
            pass
        finally:
            out_file.close()
            



if __name__ == "__main__":
    
    (backup_name, export_file) = tuple(sys.argv[1:])
    print(backup_name, export_file)
    if(not (file_exists(backup_name))):
        print('Backup file not found : ', backup_name)

    xva = tarfile.open(backup_name)
    xcp_restore = xcp_restore(backup_name, xva)

    print("Getting Files info from : ", backup_name)

    files_data = xcp_restore.get_filedata()

    if(not isinstance(files_data, (list, dict, tuple))):
        print("Files info not found in the backup file")

    print("Following Files Found : ", files_data, "\n",len(files_data), "Files Present")

    name = "disk_"
    count = 0
    for file in files_data:
        print(str(file), int(files_data[file]), str(name+str(count)))
        xcp_restore.write_file(str(file), int(files_data[file]), str(name+str(count)))
        count += 1
        
    xva.close()
        

    


