#!/usr/bin/env python
###############################################################################
# (c) Copyright 2016 CERN                                                     #
#                                                                             #
# This software is distributed under the terms of the GNU General Public      #
# Licence version 3 (GPL Version 3), copied verbatim in the file "COPYING".   #
#                                                                             #
# In applying this licence, CERN does not waive the privileges and immunities #
# granted to it by virtue of its status as an Intergovernmental Organization  #
# or submit itself to any jurisdiction.                                       #
###############################################################################

import os
import sys

from os.path import join
from json import dump

from subprocess import call
from optparse import OptionParser

parser = OptionParser()

parser.allow_interspersed_args = False
parser.add_option('--dir', action='store')
parser.add_option('--build-description', action='store')

prog = os.path.basename(sys.argv[0])
print prog, 'args:', sys.argv

opts, args = parser.parse_args()

rc = call(args)

if not os.path.exists(opts.dir):
    os.makedirs(opts.dir)
with open(join(opts.dir, '{0}.report.json'.format(prog)), 'w') as report:
    dump({
        prog: sys.argv,
        'cmd': args,
        'dir': opts.dir,
        'desc': opts.build_description,
        'retcode': rc
    }, report)

sys.exit(rc)
