#!/usr/bin/python3

import argparse
import os
import sys

sys.path.insert(0, ("/usr/lib64/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="""\
Default download cache is "/dlcache" and unpacked images "/img", appended to
$CH_GROW_STORAGE if set, else %s.
""" % ch.storage_default())
   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",
                   default=(ch.storage_env() + "/dlcache"),
                   help="download cache directory (manifests and layers)")
   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=(ch.storage_env() + "/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:   %s
destination:     %s
""" % (image.ref, image.unpack_path))
   ch.DEBUG("""\
use cache:       %s
download cache:  %s
manifest:        %s
""" % (not args.no_cache, image.download_cache, image.manifest_path))
   image.pull_to_unpacked(use_cache=(not args.no_cache))
   ch.INFO("done")


## Bootstrap ##

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