#!/usr/bin/env python

from __future__ import print_function

import os
import os.path
import re
import sys

def tag_from_path(path):
   (dirname, basename) = os.path.split(path)
   parent_dir = os.path.basename(dirname)
   (basicname, extension) = os.path.splitext(basename)
   extension = extension[1:]  # remove leading dot, if any
   assert (basicname in ("Build", "Dockerfile", "Docker_Pull"))
   if (parent_dir in ("", ".", "test")):
      assert (extension != "")
      return extension
   else:
      if (extension == ""):
         return parent_dir
      else:
         return (parent_dir + "-" + extension)


mode = sys.argv[1]

if (mode == 'tag'):
   print(tag_from_path(sys.argv[2]))
   sys.exit(0)

print("""\
# Do not edit this file; it's autogenerated.

load common
""")

for path in sys.argv[2:]:

   (dirname, basename) = os.path.split(path)
   if (dirname == ""): dirname = "."
   tag = tag_from_path(path)

   # Find scope
   with open(path) as fp:
      m = re.search(r"ch-test-scope: (skip|quick|standard|full)", fp.read())
      if (m is None):
         print("%s: no valid scope specified" % path, file=sys.stderr)
         sys.exit(1)
      scope = m.group(1)

   # Build a tarball: different test for each type.
   if (mode == "build"):
      if ("Build" in basename):
         template = """\
@test 'custom build %(tag)s' {
    scope %(scope)s
    tarball=$ch_tardir/%(tag)s.tar.gz
    pq=$ch_tardir/%(tag)s.pq_missing
    workdir=$ch_tardir/%(tag)s.tmp
    rm -f "$pq"
    mkdir "$workdir"
    cd "%(dirname)s"
    run ./%(basename)s "$PWD" "$tarball" "$workdir"
    echo "$output"
    rm -Rf "$workdir"
    if [[ $status -eq 65 ]]; then
         touch "$pq"
         skip 'prerequisites not met'
    fi
    [[ $status -eq 0 ]]
}"""
      elif ("Dockerfile" in basename or "Docker_Pull" in basename):
         if ("Dockerfile" in basename):
            template = """\
@test 'ch-build %(tag)s' {
    scope %(scope)s
    need_docker %(tag)s
    ch-build -t %(tag)s --file="%(path)s" "%(dirname)s"
    sudo docker tag %(tag)s "%(tag)s:$ch_version_docker"
    docker_ok %(tag)s
}"""
         else:
            assert ("Docker_Pull" in basename)
            with open(path) as fp:
               addr = fp.readline().rstrip()
            template = """\
@test 'docker pull %(tag)s' {
    scope %(scope)s
    need_docker %(tag)s
    sudo docker pull %(addr)s
    sudo docker tag %(addr)s %(tag)s
    sudo docker tag %(tag)s "%(tag)s:$ch_version_docker"
    docker_ok %(tag)s
}"""
         template += """
@test 'ch-docker2tar %(tag)s' {
    scope %(scope)s
    need_docker
    tarball="$ch_tardir/%(tag)s.tar.gz"
    ch-docker2tar %(tag)s "$ch_tardir"
    tarball_ok "$tarball"
}"""
      else:
         assert False, "unknown build type"
      print("\n" + template % locals())

   # Unpack tarball and run: same for all types.
   if (mode == "run"):
      print()
      print("""\
@test 'ch-tar2dir %(tag)s' {
    scope %(scope)s
    prerequisites_ok %(tag)s
    ch-tar2dir "$ch_tardir/%(tag)s.tar.gz" "$ch_imgdir"
}
@test 'ch-run %(tag)s /bin/true' {
    scope %(scope)s
    prerequisites_ok %(tag)s
    img="$ch_imgdir/%(tag)s"
    ch-run "$img" /bin/true
}""" % locals())
