/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#else
// These need to be made something sensible, like reading a value from
// the registry. But for now, get things going with a local definition.
namespace {
const char *QPIDD_CONF_FILE = "qpid_broker.conf";
const char *QPIDD_MODULE_DIR = ".";
}
#endif
#include "qpidd.h"
#include "qpid/Exception.h"
#include "qpid/Options.h"
#include "qpid/Plugin.h"
#include "qpid/sys/IntegerTypes.h"
#include "qpid/sys/LockFile.h"
#include "qpid/sys/windows/check.h"
#include "qpid/broker/Broker.h"

#include <iostream>

using namespace qpid::broker;

BootstrapOptions::BootstrapOptions(const char* argv0)
  : qpid::Options("Options"),
    common("", QPIDD_CONF_FILE),
    module(QPIDD_MODULE_DIR),
    log(argv0)
{
    add(common);
    add(module);
    add(log);
}

// Local functions to set and get the pid via a LockFile.
namespace {

const std::string TCP = "tcp";

std::string brokerPidFile(std::string piddir, uint16_t port)
{
    std::ostringstream path;
    path << piddir << "\\broker_" << port << ".pid";
    return path.str();
}

}

struct ProcessControlOptions : public qpid::Options {
    bool quit;
    bool check;
    std::string piddir;
    //std::string transport;   No transport options yet - TCP is it.

    ProcessControlOptions()
        : qpid::Options("Process control options"),
          quit(false),
          check(false) //, transport(TCP)
    {
        char *tempDir = ::getenv("TEMP");

        if (tempDir == 0)
            piddir = "C:\\WINDOWS\\TEMP";
        else
            piddir = tempDir;
        piddir += "\\qpidd";

        // Only have TCP for now, so don't need this...
          //            ("transport", optValue(transport, "TRANSPORT"), "The transport for which to return the port")
        addOptions()
            ("pid-dir", qpid::optValue(piddir, "DIR"), "Directory where port-specific PID file is stored")
            ("check,c", qpid::optValue(check), "Prints the broker's process ID to stdout and returns 0 if the broker is running, otherwise returns 1")
            ("quit,q", qpid::optValue(quit), "Tells the broker to shut down");
    }
};

struct QpiddWindowsOptions : public QpiddOptionsPrivate {
    ProcessControlOptions control;
    QpiddWindowsOptions(QpiddOptions *parent) : QpiddOptionsPrivate(parent) {
        parent->add(control);
    }
};

QpiddOptions::QpiddOptions(const char* argv0)
  : qpid::Options("Options"),
    common("", QPIDD_CONF_FILE),
    module(QPIDD_MODULE_DIR),
    log(argv0)
{
    add(common);
    add(module);
    add(broker);
    add(log);

    platform.reset(new QpiddWindowsOptions(this));
    qpid::Plugin::addOptions(*this);
}

void QpiddOptions::usage() const {
    std::cout << "Usage: qpidd [OPTIONS]" << std::endl << std::endl
              << *this << std::endl;
}

int QpiddBroker::execute (QpiddOptions *options) {
    // Options that affect a running daemon.
    QpiddWindowsOptions *myOptions =
      reinterpret_cast<QpiddWindowsOptions *>(options->platform.get());
    if (myOptions == 0)
        throw qpid::Exception("Internal error obtaining platform options");

    if (myOptions->control.check || myOptions->control.quit) {
        // Relies on port number being set via --port or QPID_PORT env variable.
        qpid::sys::LockFile getPid (brokerPidFile(myOptions->control.piddir,
                                                  options->broker.port),
                                    false);
        pid_t pid = getPid.readPid();
        if (pid < 0) 
            return 1;
        if (myOptions->control.check)
            std::cout << pid << std::endl;
        if (myOptions->control.quit)
          std::cout << "Need to stop pid " << pid << std::endl;
        return 0;
    }

    boost::intrusive_ptr<Broker> brokerPtr(new Broker(options->broker));
    if (options->broker.port == 0)
        options->broker.port = brokerPtr->getPort("");
    std::cout << options->broker.port << std::endl;

    qpid::sys::LockFile myPid(brokerPidFile(myOptions->control.piddir,
                                            options->broker.port),
                              true);
    myPid.writePid();
    brokerPtr->run();
    return 0;
}
