#!/usr/bin/env python

"""Copy a raster with various options."""

import rasterio


def main(source, destination, opts, template=None, log=None):
    """Copy from source to destination with new options"""

    with rasterio.drivers():

        try:

            with rasterio.open(source) as src:

                # First, copy the opts to the destination's kwargs.
                kwargs = src.meta.copy()
                kwargs.update(opts)

                # If there's a template file, overlay its georeferencing.
                if template is not None:
                    with rasterio.open(template) as tmpl:
                        kwargs['transform'] = tmpl.transform
                        kwargs['crs'] = tmpl.crs

                # Write to the destination.
                # TODO: use shortcut to source buffer.
                with rasterio.open(destination, 'w', **kwargs) as dst:
                    for i in src.indexes:
                        dst.write_band(i, src.read_band(i))

        except:
            log.exception("rio_cp failed, exception caught")
            return 1

    return 0

if __name__ == '__main__':

    import argparse
    import logging
    import sys

    parser = argparse.ArgumentParser(
        description="Copy raster file with options")
    parser.add_argument(
        'source',
        metavar='SOURCE',
        help="Source file name")
    parser.add_argument(
        'destination',
        metavar='DESTINATION',
        help="Destination file name")
    # TODO: add a short option for the following.
    parser.add_argument(
        '--template-file',
        metavar='FILE',
        help="Use a georeferenced file as a template")
    parser.add_argument(
        '-z',
        action='store_true',
        help="Compress destination using LZW")
    parser.add_argument(
        '-v',
        action='store_true',
        help="Verbose logging")
    args = parser.parse_args()

    if args.v:
        logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
    else:
        logging.basicConfig(stream=sys.stderr, level=logging.INFO)
    logger = logging.getLogger('rio_cp')

    # TODO: quick check of filenames before we call main().

    options = {}
    if args.z:
        options['compress'] = 'LZW'

    # TODO: support other formats.
    options['driver'] = 'GTiff'

    sys.exit(
        main(
            args.source,
            args.destination,
            options,
            args.template_file,
            log=logger))

