#!/usr/bin/env python
#
# Copyright 2014-2017 AT&T Intellectual Property
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import traceback

from oslo_log import log

from valet.common.conf import get_logger
from valet.engine.optimizer.ostro.ostro import Ostro
from valet.engine.optimizer.ostro_server.configuration import Config
from valet.engine.optimizer.ostro_server.daemon import Daemon

LOG = log.getLogger(__name__)


class OstroDaemon(Daemon):
    """Daemon for Valet Engine."""

    def run(self):
        """Run the daemon."""
        LOG.info("Valet Engine is launched")
        try:
            ostro = Ostro(config)
        except Exception:
            LOG.error(traceback.format_exc())

        if ostro.bootstrap() is False:
            LOG.error("Valet Engine bootstrap failed")
            sys.exit(2)

        # Write pidfile
        pid = str(os.getpid())
        file(self.pidfile, 'w+').write("%s\n" % pid)

        ostro.run_ostro()


def verify_dirs(list_of_dirs):
    """If a directory in the list does not exist, create it."""
    for d in list_of_dirs:
        try:
            if not os.path.exists(d):
                os.makedirs(d)
        except OSError:
            print("Error while verifying: " + d)
            sys.exit(2)


if __name__ == "__main__":
    # Configuration
    try:
        config = Config()
        logger = get_logger("ostro_daemon")
        config_status = config.configure()
        if config_status != "success":
            print(config_status)
            sys.exit(2)

        # Verify directories
        dirs_list = [config.logging_loc, config.resource_log_loc,
                     config.app_log_loc, os.path.dirname(config.process)]
        verify_dirs(dirs_list)

        # Start daemon process
        daemon = OstroDaemon(config.priority, config.process, logger)

        exit_code = {
            'start': daemon.start,
            'stop': daemon.stop,
            'restart': daemon.restart,
            'status': daemon.status,
        }[config.command]()
        exit_code = exit_code or 0

    except Exception:
        print(traceback.format_exc())
        exit_code = 2

    sys.exit(int(exit_code))