#! /usr/bin/env python

import os
import sys
import argparse

import smacha

if __name__ == '__main__':
    # Parse arguments
    arg_parser = argparse.ArgumentParser(description='SMACHA Extract: Extract a container state from a script and ' +
                                                     'save it as a sub-script.')

    arg_parser.add_argument('script_file',
                            action='store',
                            help='SMACHA script (yaml file).')

    arg_parser.add_argument('state',
                            action='store',
                            help='Name of container state to be extracted.')

    arg_parser.add_argument('-s', '--scripts',
                            nargs = '*',
                            dest='script_dirs',
                            action='store',
                            default=[],
                            help='SMACHA script directories (directories containing yaml files).')

    arg_parser.add_argument('-sub', '--sub-script-output',
                            dest='sub_script_output_file',
                            action='store',
                            default='./smacha_extract_sub_script_output.yml',
                            help='Generated SMACHA sub-script output (YAML file).')

    arg_parser.add_argument('-sup', '--super-script-output',
                            dest='super_script_output_file',
                            action='store',
                            default='./smacha_extract_super_script_output.yml',
                            help='Generated SMACHA super-script output (YAML file).')


    args = arg_parser.parse_args()

    # Load parser
    parser = smacha.Parser(script_dirs=args.script_dirs)

    # Load and parse SMACHA script
    script_str, _ = parser.load(args.script_file)
    script = parser.parse(script_str)

    # Use the extract() method in the parser to perform the extraction
    sub_script, super_script = parser.extract(script, args.state, sub_script_filename=args.sub_script_output_file)

    # Write the updated super-script to a YAML file
    parser.dump(super_script, output_file=args.super_script_output_file)

    # Write the sub-script to a YAML file
    parser.dump([sub_script], output_file=args.sub_script_output_file)
