#!/usr/bin/env python
# -*- coding:iso-8859-1

'''
Copyright (c) 2014 Nicolas Höning

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import sys
import signal

from stosim import __version__
from stosim.sim import commands, utils



def signal_handler(signal, frame):
    ''' gently exiting, e.g. when CTRL-C was pressed in FJD.  '''
    commands.we_exited[0] = True


if __name__ == "__main__":

    signal.signal(signal.SIGINT, signal_handler)
    args = utils.read_args()
    if not args.version:
        utils.check_conf(args.folder)

    # define standard program (if no options are set)
    if (args.run == args.ttests == args.more == args.snapshot == args.kill\
       == args.list == args.resume == args.status == False and args.plots is None):
        args.run = args.ttests = True
        args.plots = []

    # do these if they are given:
    fine = True
    if args.version:
        print "[StoSim] Version: {}".format(__version__)
        sys.exit(0)
    elif args.status:
        fine = commands.status(args.folder)
    elif args.resume:
        fine = commands.resume(args.folder)
    elif args.more:
        fine = commands.run_more(args.folder)
    elif args.run:
        utils.check_for_older_data(args.folder, more=args.more)
        commands.prepare_folders_and_jobs(args.folder)
        fine = commands.run(args.folder)
    elif args.snapshot:
        fine = commands.snapshot(args.folder)
    elif args.kill:
        fine = commands.kill(args.folder)
    elif args.list:
        fine = commands.list_data(args.folder)

    if fine and not commands.we_exited[0]:
        if args.plots is not None:
            commands.make_plots(args.folder, plot_nrs=args.plots)
        if args.ttests:
            commands.run_ttests(args.folder)
