#ifndef INCLUDED_CRON_
#define INCLUDED_CRON_

#include <memory>
#include <thread>
#include <set>
#include <mutex>
#include <iosfwd>
#include <vector>

#include <bobcat/fork>
#include <bobcat/hmacbuf>
#include <bobcat/localserversocket>
#include <bobcat/pipe>
#include <bobcat/signal>
                                       
#include "../udsreq/udsreq.h"
#include "../crondata/crondata.h"

namespace FBB
{
    class DateTime;
    class IFdStream;
    class OFdStream;
}

class CronEntry;
class CronData;
class Options;

    // IPCFunction defines the function requests sent by ssh-cron
    // or set by ssh-cron not running as daemon

class Cron: private UDSReq, public FBB::Fork, public FBB::SignalHandler
{
    using SizeSet = std::set<size_t>;
    using EntryVect = std::vector<CronEntry const *>;

    Options &d_options;

    std::mutex d_mutex;
    FBB::LocalServerSocket d_server;
    
    std::string d_passphrase;
    std::unique_ptr<FBB::IFdStream> d_in;
    std::unique_ptr<FBB::OFdStream> d_out;

    FBB::Pipe d_childInput;         // child reads STDIN from this pipe

    CronData d_cronData;

    std::ostream *d_toChild = 0;

    static std::string s_agent;
    static void (Cron::*s_request[])();     // error, list, reload, terminate

    public:
        Cron(std::string const &passphrase);
        ~Cron() override;

    private:
        void childRedirections()            override;
        void childProcess()                 override;
        void parentProcess()                override;
        void signalHandler(size_t signal)   override;

        bool add(CronEntry const &entry, FBB::DateTime const &now);

        void childExec(std::string const &line);

        void cronCmd(CronEntry const &entry);       // cmd sent to the child
        void cronCmds();                // separate thread (parentprocess.cc)

        EntryVect cronJobs();           // return crontab entries to process
        void defineRun();               // defines the _run_ bash fun.
        void error();

        std::ostream &idmsg() const;    // imsg << basneame :           // .ih

        bool load(std::string const &cronFile); // load a cron file
        void list();
        void reload();
        void request(std::string const &cmd);
        void terminate();
        bool verifyPassphrase();

        static bool call(size_t value, SizeSet const &specified);       // .ih
        static std::string hmac(std::string const &passphrase);
};

//std::ostream &scheduler() const;    // d_options.msg() << "scheduler: "
//void sendChild(CronEntry const &entry);

//void popQueue(std::stop_token stop);    
//static std::string hmac(std::string const &passPhrase);

#endif


