#   Copyright (c) 2013 Axel Wachtler
#   All rights reserved.
#
#   Redistribution and use in source and binary forms, with or without
#   modification, are permitted provided that the following conditions
#   are met:
#
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the authors nor the names of its contributors
#     may be used to endorse or promote products derived from this software
#     without specific prior written permission.
#
#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
#   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#   POSSIBILITY OF SUCH DAMAGE.

# $Id$
"""
This script unpacks and completely builds the source package

Usage:
    python test_src_pkg.py [options] uracoli-src-<version>.zip

Options:
    -h      show this help and exit
    -b BUILD_DIR
            set build directory (default: ./build)

"""


# === import ==================================================================
import sys, zipfile, os, subprocess, glob, getopt
from utilities import execute, error
# === globals =================================================================
BUILD_DIR = "build/arduino"

# === functions ===============================================================

# === classes =================================================================

# === init ====================================================================

if __name__ == "__main__":
    do_exit = False
    opts,args = getopt.getopt(sys.argv[1:],"hb:")
    for o,v in opts:
        if o == "-b":
            BUILD_DIR = v
        elif o == "-h":
            print __doc__
            do_exit = True
            break

    if do_exit:
        sys.exit(0)

    arcfile = args[0]

    if not zipfile.is_zipfile(arcfile):
        error("%s is not a zipfile" % arcfile)

    zf = zipfile.ZipFile(arcfile,"r")
    if not os.path.isdir(BUILD_DIR):
        os.makedirs(BUILD_DIR)
    # unpack
    zf.extractall(BUILD_DIR)


    lf_so = open(BUILD_DIR + "/stdout.log", "w")
    lf_se = open(BUILD_DIR + "/stderr.log", "w")

    try:
        rc, so, se = execute("make -C %s/hardware/uracoli/bootloaders/radiofaro/ all" % BUILD_DIR)
        if rc != 0:
            print "Build Arduino Bootloader failed"
            print "cmd: %s" % cmd
            print "rc = %d" % rc
            print "stderr: %s" % stderr.replace("\n", "\nstderr: ")
            print "stdout: %s" % stdout.replace("\n", "\nstdout: ")
            fatal_error("Build Arduino failed")

        lf_so.write(so)
        lf_se.write(se)

    except:
        print sys.exc_info()

    lf_so.close()
    lf_se.close()
