#!/usr/bin/env python

# If environment variable CH_TEST_OMIT is set, then avoid Dockerfiles that
# seem lengthy. This supports job time limits in Travis CI. See source code
# below for the heuristic.

from __future__ import print_function

import os
import os.path
import sys

mode = sys.argv[1]

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

load common
""")

for path in sys.argv[2:]:

   (d, f) = os.path.split(path)
   if (d == ""): d = "."

   # Find image tag.
   if (f in ("Build", "Dockerfile", "Docker_Pull")):
      tag = os.path.basename(d)         # no extension; use parent directory
   else:
      tag = os.path.splitext(f)[1][1:]  # use extension
   assert (tag != "")

   # Should we omit the test?
   try:
      if (os.environ["CH_TEST_OMIT"] in tag):
         continue
   except KeyError:
      pass

   # Build a tarball: different test for each type.
   if (mode == "build"):
      if ("Build" in f):
         template = """\
@test 'custom build %(tag)s' {
    TARBALL=$TARDIR/%(tag)s.tar.gz
    PQ=$TARDIR/%(tag)s.pq_missing
    WORKDIR=$TARDIR/%(tag)s.tmp
    rm -f $PQ
    mkdir $WORKDIR
    cd %(d)s
    run ./%(f)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 f or "Docker_Pull" in f):
         if ("Dockerfile" in f):
            template = """\
@test 'ch-build %(tag)s' {
    need_docker %(tag)s
    ch-build -t %(tag)s --file=%(path)s ..
    docker_ok %(tag)s
}"""
         else:
            assert ("Docker_Pull" in f)
            with open(path) as fp:
               addr = fp.readline().rstrip()
            template = """\
@test 'docker pull %(tag)s' {
    need_docker %(tag)s
    sudo docker pull %(addr)s
    sudo docker tag %(addr)s %(tag)s
}"""
         template += """
@test 'ch-docker2tar %(tag)s' {
    need_docker
    TARBALL=$TARDIR/%(tag)s.tar.gz
    ch-docker2tar %(tag)s $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' {
    prerequisites_ok %(tag)s
    ch-tar2dir $TARDIR/%(tag)s.tar.gz $IMGDIR
}
@test 'ch-run %(tag)s /bin/true' {
    prerequisites_ok %(tag)s
    IMG=$IMGDIR/%(tag)s
    ch-run $IMG /bin/true
}""" % locals())
