//
// Main.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013-2016 Carsten Sonne Larsen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Text;
using Ntp.Analyzer.Log;
using Ntp.Analyzer.Process;
using Ntp.Process;
using Ntp.System;

namespace Ntp.Analyzer.Cli
{
    /// <summary>
    /// Entry point for CLI application.
    /// </summary>
    public static class MainClass
    {
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main (string[] args)
        {
            if (args.Length > 2) {
                ShowUsage ();
                return;
            }

            if (args.Length >= 1 && args[0] == "help") {
                ShowUsage ();
                return;
            }

            string name = (args.Length > 1) ? args [1] : "NTPA_DEF";

            if (args.Length >= 1 && args [0] == "stop") {
                bool success = InterLock.Release (name, new ActivityLog ());
                if (!success) {
                    Console.WriteLine ("Could not stop daemon.");
                }
                return;
            }

            string configFile = (args.Length > 0) ? args [0] : "/etc/ntpa.conf";
            int pid = ProcessInfo.ProcessId;
                    
            Main main = new Main (configFile, pid, name);
            main.Start ();
        }
            
        private static void ShowUsage()
        {
            Console.WriteLine("NTP Analyzer Daemon.");
            Console.WriteLine("Usage: ntpa [configuration file | stop] [instance name]");
        }
    }
}