#!/usr/bin/python3

import argparse
import os
import sys

sys.path.insert(0, (  os.path.dirname(os.path.abspath(__file__))
                    + "/../lib/charliecloud"))
import charliecloud as ch


def main():
   ap = argparse.ArgumentParser(
           formatter_class=argparse.RawDescriptionHelpFormatter,
           description="Pull and flatten image from repository to local filesystem.",
           epilog="""\
environment variables:
  CH_GROW_STORAGE     used to compute defaults for --dl-cache and --unpack-dir
""")
   ap.add_argument("image", metavar="IMAGE_REF",
                   help="image reference")
   ap.add_argument("--dependencies", action=ch.CLI_Dependencies,
                   help="print any missing dependencies and exit")
   ap.add_argument("--dl-cache", metavar="DIR",
                   help="download cache directory (manifests and layers)",
                   default=(  os.environ.get("CH_GROW_STORAGE",
                                             "/var/tmp/ch-grow")
                            + "/dlcache"))
   ap.add_argument("--no-cache", action="store_true", default=False,
                   help="always download, even if cached files exist")
   ap.add_argument("--image-subdir", metavar="DIR",
                   help="subdirectory of --unpack-dir to hold unpacked image")
   ap.add_argument("--parse-ref-only",
                   action="store_true",
                   help="parse image reference, print report, and exit")
   ap.add_argument("--unpack-dir", metavar="DIR",
                   help="directory containing unpacked images",
                   default=(  os.environ.get("CH_GROW_STORAGE",
                                             "/var/tmp/ch-grow")
                              + "/img"))
   ap.add_argument("-v", "--verbose", action="count", default=0,
                   help="print extra chatter (can be repeated)")
   ap.add_argument("--version", action=ch.CLI_Version,
                   help="print version and exit")
   if (len(sys.argv) < 2):
      ap.print_help(file=sys.stderr)
      sys.exit(1)

   args = ap.parse_args()
   ch.verbose = args.verbose

   ch.dependencies_check()

   ref = ch.Image_Ref(args.image)
   if (args.parse_ref_only):
      print(ref.as_verbose_str)
      sys.exit(0)

   image = ch.Image(ref, args.dl_cache, args.unpack_dir, args.image_subdir)
   ch.INFO("pulling image: " + str(image.id))
   ch.DEBUG("""\
download cache:  %s
unpack path:     %s
manifest:        %s
""" % (image.download_cache, image.unpack_path, image.manifest_path))
   image.download(not args.no_cache)
   image.flatten()
   ch.INFO("done")


## Bootstrap ##

if (__name__ == "__main__"):
   main()
