#   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$
"""
Usage:
    python %s [OPTIONS] CFG_FILE

Options:
    -f
        force flash (default no)
    -b bin_dir
        set directory to find binary files (default: ./install/bin)
    -h
        show help and exit
    -v
        show version and exit

"""

# === import ==================================================================
import sys, os, getopt, subprocess
from ConfigParser import ConfigParser

# === globals =================================================================

# === functions ===============================================================
def test_init(help_str = None, version_str = None):
    global ERROR
    ERROR = 0
    cfg_data = None
    do_exit = False
    force_flash = 0
    bin_dir = None
    prog_name = os.path.basename(sys.argv[0])
    opts,args = getopt.getopt(sys.argv[1:], "fhvb:")

    for o,v in opts:
        if o == "-f":
            force_flash = 1
        elif o == "-b":
            bin_dir = v
        elif o == "-h":
            print  help_str + \
                   __doc__ % prog_name
            do_exit = True
        elif o == "-v":
            print prog_name, "VERSION:", version_str
            do_exit = True
    if not do_exit:
        assert(os.path.exists(args[0]), "config file not found")
        cfg_data = ConfigParser()
        cfg_data.read(args[0])

        cfg_data.set("CONFIG", "force_flash", str(force_flash))
        cfg_data.set("CONFIG", "prog_name", prog_name)
        if bin_dir:
            assert(os.path.isdir(bin_dir), "bin_dir (-b) file not found")
            cfg_data.set("CONFIG", "bin_dir", bin_dir)

    return cfg_data

def test_error(check_ok, msg):
    global ERROR
    if not check_ok:
        rv = 1
        ERROR += 1
        print "... fail: %s" % msg
    else:
        rv = 0
        print "... OK"
    return rv

def test_get_errors():
    return ERROR


def error(msg, excode=1):
    print >> sys.stderr, msg
    sys.exit(excode)

def fatal_error(msg, excode=1):
    print >> sys.stderr, msg
    sys.exit(excode)


def execute(cmd):
    print "# %s" % cmd
    proc = subprocess.Popen( cmd, shell=True, stderr=subprocess.PIPE,
                             stdout = subprocess.PIPE)
    stdout, stderr = proc.communicate()
    return proc.returncode, stdout, stderr

def ser_get_text(sport, n = 1):
    rv = sport.read(n)
    while sport.inWaiting():
        rv += sport.read()
    return rv

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

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