#!/usr/bin/env python

from __future__ import print_function

import os
import os.path
import re
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 != "")

   # 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 f):
         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 "%(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' {
    scope %(scope)s
    need_docker %(tag)s
    ch-build -t %(tag)s --file="%(path)s" ..
    sudo docker tag %(tag)s "%(tag)s:$ch_version_docker"
    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' {
    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())
