#!/usr/bin/env python
"""
This script runs all the examples in examples directory.
It should be run from the top-level directory (containing setup.py).
"""

import glob
import os
import sys
import subprocess

try:
    from subprocess import DEVNULL # py3k
except ImportError:
    DEVNULL = open(os.devnull, 'wb')

class ExampleTester:
    failed = []
    passed = 0
    rootdir =  os.getcwd()

    def __init__(self):
        subprocess.check_call([sys.executable, "setup.py", "build_ext", "--inplace"])
        os.environ["PYTHONPATH"] = self.rootdir

    def run(self, d, cmd, **kwargs):
        """
        Run command cmd in directory d.
        """
        print("running %s in %s ..." % (cmd, d))
        os.chdir(os.path.join(self.rootdir, d))
        r = subprocess.call([sys.executable] + cmd, **kwargs)
        if r != 0:
            self.failed.append((d, cmd, r))
        else:
            self.passed += 1
        os.chdir(self.rootdir)
        return r

    def report(self):
        print(self.passed, "example(s) ran successfully")
        if len(self.failed) > 0:
            print("failed examples:")
            for ex in self.failed:
                print("  %s in %s failed with exit code %s" % (ex[1], ex[0], ex[2]))
            sys.exit(2)
        sys.exit(0)

def main():
    t = ExampleTester()
    t.run("examples/compress", ["test-compress.py"], stdout=DEVNULL)
    t.run("examples/vgroup", ["vgwrite.py"])
    t.run("examples/vgroup", ["vgread.py", "inventory.hdf"], stdout=DEVNULL)
    t.run("examples/inventory", ["inventory_1-1.py"])
    t.run("examples/inventory", ["inventory_1-2.py"])
    t.run("examples/inventory", ["inventory_1-3.py"])
    t.run("examples/inventory", ["inventory_1-4.py"], stdout=DEVNULL)
    t.run("examples/inventory", ["inventory_1-5.py"], stdout=DEVNULL)
    t.run("examples/txttohdf", ["txttohdf.py"])

    # These HDF files were generated by above examples
    for g in sorted(glob.glob("examples/*/*.hdf")):
        hdffile = os.path.join("../..", g)
        t.run("examples/hdfstruct", ["hdfstruct.py", hdffile], stdout=DEVNULL)

    t.report()

if __name__ == '__main__':
    main()
