from osgeo import gdal
import codecs

def read_vsimem(filepath):
    """ Read GDAL vsimem files """
    vsifile = gdal.VSIFOpenL(filepath,'r')
    gdal.VSIFSeekL(vsifile, 0, 2)
    vsileng = gdal.VSIFTellL(vsifile)
    gdal.VSIFSeekL(vsifile, 0, 0)
    return gdal.VSIFReadL(1, vsileng, vsifile)

def write_vsimem(filepath,data):
    """ Write GDAL vsimem files """
    vsifile = gdal.VSIFOpenL(filepath,'w')
    print('vsifile ######', vsifile)
    size = len(data)
    gdal.VSIFWriteL(data, 1, size, vsifile)
    return gdal.VSIFCloseL(vsifile)

def create_copy(ds, drivername, filepath, creation_options=[]):
    """ Create a copy of a GDAL dataset """
    drv = gdal.GetDriverByName(drivername)
    return drv.CreateCopy(filepath, ds, strict=0, options=creation_options)

def copy_everything(inpath, fixpath, outpath):
    """ Copy _all_ georeferencing and other metadata from one file to another
        Assumes files match exactly...!
    """
    # vrtpath= '/vsimem/foo.vrt'
    inds = gdal.Open(inpath)
    vrtds = create_copy(inds, 'VRT', vrtpath)
    vrtxml = codecs.decode(read_vsimem(vrtpath))
    # print(type(vrtxml))
    # print(vrtxml)
    file_name = inpath.split('/')[-1]
    vrt_name = vrtpath.split('/')[-1]
    replace = vrtxml.replace(file_name, vrt_name)
    print(replace)
    write_vsimem(vrtpath, replace)
    #USE_SRC_CODESTREAM=YES/NO only available in GDAL >= 2.0 (EXPERIMENTAL!)

    outds = create_copy(vrtds, 'JP2OpenJPEG', outpath, creation_options=['USE_SRC_CODESTREAM=YES'])

vrtpath= '/home/data-engineer/workspace/foo.vrt'
fixpath= '/home/data-engineer/workspace/fixpath.jp2'
copy_everything(filepath, vrtpath, '/home/data-engineer/workspace/new.jp2' )