#!/usr/bin/python3

# Copyright (C) 2019-2020
# * Felix Delattre <felix@delattre.de>
# * W. Martin Borgert <debacle@debian.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import argparse
import asyncio
import sys
import sdnotify

sys.path.insert(0, "/usr/lib/sms4you")
from sms4you.core.configuration import Configuration  # noqa: E402
from sms4you.core.logging import Logging  # noqa: E402
from sms4you.core.gateway_factory import GatewayFactory  # noqa: E402

VERSION = "0.0.7"


def get_args():
    parser = argparse.ArgumentParser(
        prog="sms4you",
        description="Personal gateway connecting SMS with XMPP or email..",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        "-c", "--configfile", help="configuration file", default="/etc/sms4you/sms4you.ini"
    )
    parser.add_argument("-d", "--debug", help="set log level to debug", action="store_true")
    return parser.parse_args()


def main():
    args = get_args()

    # Validate and prepare configuration
    config = Configuration(args.configfile, VERSION)

    # Setup logging
    logger = Logging(args.debug)

    # Initiate the asynchronous event loop
    loop = asyncio.get_event_loop()

    # Initiate gateways for communication through an object factory
    factory = GatewayFactory(config, loop, logger)
    sms_gateway = factory.get_sms_gateway()
    other_gateway = factory.get_other_gateway()

    # Setup gateways
    sms_gateway.setup(other_gateway)
    other_gateway.setup(sms_gateway)

    # After configuration is done, tell systemd, that we are ready
    sdnotify.SystemdNotifier().notify("READY=1")

    # Run loop until abborted and close afterwards
    loop.run_forever()
    loop.close()


if __name__ == "__main__":
    main()
