#! /usr/libexec/platform-python -s
#
# Copyright (c) 2020,2021 - Adjacent Link LLC, Bridgewater, New Jersey
# 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 Adjacent Link LLC 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.
#

from __future__ import absolute_import, division, print_function
import argparse
import os
import sys
from emane_node_director.batchrunner import BatchRunner
from emane_node_director.shell import Shell

try:
    from emane.events import EventService,EventServiceException
except:
    from emanesh.events import EventService,EventServiceException


def main():
    usage = '''
Move emane NEM locations.'''

    parser = argparse.ArgumentParser( \
                prog='emane-node-director',
                description=usage,
                formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('--eventservicedevice',
                        metavar='DEVICE',
                        default='backchan0',
                        help='''The network device used to send EMANE
                        events. Default: backchan0''')
    parser.add_argument('--eventservicegroup',
                        metavar='GROUP',
                        default='224.1.2.8:45703',
                        help='''The multicast group (address and port)
                        for sending location events. Default:
                        224.1.2.8:45703''')
    parser.add_argument('--latlonstep',
                        metavar='LATLONSTEP',
                        type=float,
                        default=0.001,
                        help='''The step (in degrees) taken for each
                        change in latitude or longitude position.
                        Default: 0.001 degrees.''')
    parser.add_argument('--altstep',
                        metavar='ALTSTEP',
                        type=float,
                        default=1.0,
                        help='''The altitude step (in meters) taken
                        for each change in position. Default: 1
                        meter.''')
    parser.add_argument('--anglestep',
                        metavar='ANGLESTEP',
                        type=float,
                        default=0.01,
                        help='''The angle (in degress), taken for each
                        elevation, azimuth, pitch, roll, yaw and
                        antenna pointing steps.  Default: 0.01
                        degrees.''')
    parser.add_argument('--timestep',
                        metavar='TIMESTEP',
                        type=float,
                        default=5.0,
                        help='''When writing the current state to the EEL
                        format STATEFILE, advance time by TIMESTEP for
                        each write. Default: 5.0.''')
    parser.add_argument('--statefile',
                        metavar='STATEFILE',
                        default='state.eel',
                        help='''EEL format file where current state is
                        written on each invocation of "write"
                        command. Default: state.eel''')
    parser.add_argument('--starttime',
                        default=None,
                        metavar='STARTTIME',
                        help='''In batch mode, start batch command
                        processing at STARTTIME.  STARTTIME is
                        HH:MM:SS with HH in range 00 to 23. Default:
                        None (run immediately).''')
    parser.add_argument('eelfile',
                        metavar='EELFILE',
                        help='''The EELFILE used for nem initial postions.''')
    parser.add_argument('--batch',
                        metavar='BATCHFILE',
                        default=None,
                        help='''Run in batch mode. BATCHFILE is a list
                        of director commands, (one per line) with a
                        prepended time number that dictates when the
                        command is issued.''')
    parser.add_argument('--quiet',
                        default=False,
                        action='store_true',
                        help='Run with quieter output')
    parser.add_argument('--pathloss',
                        metavar='ALGORITHM',
                        choices=['2ray', 'freespace', 'none'],
                        default='none',
                        help='''Calculate and send pathloss events
                        based on current location and antenna pointing
                        when "2ray" or "freespace" algorithms are
                        specified.  Pathloss events are not sent when
                        "none" (the default).''')
    parser.add_argument('--frequency',
                        metavar='FREQUENCY',
                        type=int,
                        default=2347000000,
                        help='''Specifies the frequency (Hz) at which
                        pathloss values are computed when the
                        frequency argument is set to freespace.''')

    args = parser.parse_args()

    mcgroup,port = args.eventservicegroup.split(':')

    service = None

    try:
        service = EventService((mcgroup, int(port), args.eventservicedevice))

    except EventServiceException as e:
        print(e, file=sys.stderr)

        exit(1)

    shell = Shell(service, args)

    if args.batch:
        if not os.path.exists(args.batch):
            print('Cannot find batch file "%s". Quitting.' % args.batch, file=sys.stderr)

            exit(1)

        BatchRunner(shell, args.batch).run(args.starttime)

    else:
        shell.cmdloop()


if __name__=='__main__':
    main()
