/***
    This file is part of snapcast
    Copyright (C) 2014-2025  Johannes Pohl

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
***/

// local headers
#include "common/base64.h"
#include "common/popl.hpp"
#include "common/utils/string_utils.hpp"
#include "controller.hpp"

#ifdef HAS_ALSA
#include "player/alsa_player.hpp"
#endif
#ifdef HAS_PULSE
#include "player/pulse_player.hpp"
#endif
#ifdef HAS_WASAPI
#include "player/wasapi_player.hpp"
#endif
#ifdef HAS_PIPEWIRE
#include "player/pipewire_player.hpp"
#endif
#include "player/file_player.hpp"
#ifdef HAS_DAEMON
#include "common/daemon.hpp"
#endif
#include "client_settings.hpp"
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/stream_uri.hpp"
#include "common/version.hpp"

// 3rd party headers
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/signal_set.hpp>

// standard headers
#include <algorithm>
#include <filesystem>
#include <iostream>
#include <vector>
#ifndef WINDOWS
#include <csignal>
#include <sys/resource.h>
#endif


using namespace std;
using namespace popl;
using namespace player;

using namespace std::chrono_literals;

static constexpr auto LOG_TAG = "Snapclient";

namespace
{
PcmDevice getPcmDevice(const std::string& player, const std::string& parameter, const std::string& soundcard)
{
    LOG(DEBUG, LOG_TAG) << "Trying to get PCM device for player: " << player << ", parameter: " << ", card: " << soundcard << "\n";
#if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) || defined(HAS_PIPEWIRE)
    vector<PcmDevice> pcm_devices;
#if defined(HAS_ALSA)
    if (player == player::ALSA)
        pcm_devices = AlsaPlayer::pcm_list();
#endif
#if defined(HAS_PULSE)
    if (player == player::PULSE)
        pcm_devices = PulsePlayer::pcm_list(parameter);
#endif
#if defined(HAS_WASAPI)
    if (player == player::WASAPI)
        pcm_devices = WASAPIPlayer::pcm_list();
#endif
#if defined(HAS_PIPEWIRE)
    if (player == player::PIPEWIRE)
        pcm_devices = PipeWirePlayer::pcm_list(parameter);
#endif
    if (player == player::FILE)
        return FilePlayer::pcm_list(parameter).front();
    try
    {
        // If "soundcard" can be converted to an integer,
        // try to map the device by index
        int soundcardIdx = cpt::stoi(soundcard);
        for (const auto& dev : pcm_devices)
            if (dev.idx == soundcardIdx)
                return dev;
    }
    catch (...)
    {
    }

    for (const auto& dev : pcm_devices)
        if (dev.name.find(soundcard) != string::npos)
            return dev;
#endif
    std::ignore = player;
    std::ignore = parameter;
    PcmDevice pcm_device;
    pcm_device.name = soundcard;
    return pcm_device;
}
} // namespace

#ifdef WINDOWS
// hack to avoid case destinction in the signal handler
#define SIGHUP SIGINT
const char* strsignal(int sig)
{
    switch (sig)
    {
        case SIGTERM:
            return "SIGTERM";
        case SIGINT:
            return "SIGINT";
        case SIGBREAK:
            return "SIGBREAK";
        case SIGABRT:
            return "SIGABRT";
        default:
            return "Unhandled";
    }
}
#endif

int main(int argc, char** argv)
{
#ifdef MACOS
#pragma message "Warning: the macOS support is experimental and might not be maintained"
#endif

#ifdef HAS_MDNS
    const std::string default_uri = "tcp://_snapcast._tcp";
#endif

    int exitcode = EXIT_SUCCESS;
    try
    {
        ClientSettings settings;
        string pcm_device(player::DEFAULT_DEVICE);

        OptionParser op("Usage: snapclient [options...] [url]\n\n"
                        " With 'url' = "
#ifdef HAS_OPENSSL
                        "<tcp|ws|wss>"
#else
                        "<tcp|ws>"
#endif
#ifdef HAS_MDNS
                        "://<snapserver host or IP or mDNS service name>[:port]\n"
                        " For example: 'tcp://192.168.1.1:1704', or 'ws://)homeserver.local' or 'wss://_snapcast-https._tcp'\n"
                        " If 'url' is not configured, snapclient defaults to '" +
                        default_uri + "'\n");
#else
                        "://<snapserver host or IP>[:port]\n"
                        " For example: 'tcp://192.168.1.1:1704', or 'ws://homeserver.local'\n");
#endif
        auto helpSwitch = op.add<Switch>("", "help", "Produce help message");
        auto groffSwitch = op.add<Switch, Attribute::hidden>("", "groff", "Produce groff message");
        auto versionSwitch = op.add<Switch>("v", "version", "Show version number");
        auto deprecated_host_opt = op.add<Value<string>>("h", "host", "(deprecated, use [url]) Server hostname or ip address", "");
        auto deprecated_port_opt = op.add<Value<size_t>>("p", "port", "(deprecated, use [url]) Server port", 1704);
        op.add<Value<size_t>>("i", "instance", "Instance id when running multiple instances on the same host", 1, &settings.instance);
        op.add<Value<string>>("", "hostID", "Unique host id, default is MAC address", "", &settings.host_id);
        op.add<Value<std::filesystem::path>>("", "cert", "Client certificate file (PEM format)", settings.server.certificate, &settings.server.certificate);
        op.add<Value<std::filesystem::path>>("", "cert-key", "Client private key file (PEM format)", settings.server.certificate_key,
                                             &settings.server.certificate_key);
        op.add<Value<string>>("", "key-password", "Key password (for encrypted private key)", settings.server.key_password, &settings.server.key_password);
        auto server_cert_opt =
            op.add<Implicit<std::filesystem::path>>("", "server-cert", "Verify server with CA certificate (PEM format)", "default certificates");

// PCM device specific
#if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) || defined(HAS_PIPEWIRE)
        auto listSwitch = op.add<Switch>("l", "list", "List PCM devices");
        op.add<Value<string>>("s", "soundcard", "Index or name of the PCM device", pcm_device, &pcm_device);
#endif
        op.add<Value<int>>("", "latency", "Latency of the PCM device", 0, &settings.player.latency);
#ifdef HAS_SOXR
        auto sample_format = op.add<Value<string>>("", "sampleformat", "Resample audio stream to <rate>:<bits>:<channels>", "");
#endif

        auto supported_players = Controller::getSupportedPlayerNames();
        string supported_players_str;
        for (const auto& supported_player : supported_players)
            supported_players_str += (!supported_players_str.empty() ? "|" : "") + supported_player;
        op.add<Value<string>>("", "player", supported_players_str + "[:<options>|?]", supported_players.front(), &settings.player.player_name);

// sharing mode
#if defined(HAS_OBOE) || defined(HAS_WASAPI)
        auto sharing_mode = op.add<Value<string>>("", "sharingmode", "Audio mode to use [shared|exclusive]", "shared");
#endif

        // mixer
        bool hw_mixer_supported = false;
#if defined(HAS_ALSA)
        hw_mixer_supported = true;
#endif
        std::shared_ptr<popl::Value<std::string>> mixer_mode;

        std::string mixers = "software";
        if (hw_mixer_supported)
            mixers += "|hardware";
#ifdef SUPPORTS_VOLUME_SCRIPT
        mixers += "|script";
#endif
        mixer_mode = op.add<Value<string>>("", "mixer", mixers + "|none|?[:<options>]", "software");

// daemon settings
#ifdef HAS_DAEMON
        int processPriority(-3);
        auto daemonOption = op.add<Implicit<int>>("d", "daemon", "Daemonize, optional process priority [-20..19]", processPriority, &processPriority);
        auto userValue = op.add<Value<string>>("", "user", "The user[:group] to run snapclient as when daemonized");
#endif

        // logging
        op.add<Value<string>>("", "logsink", "Log sink [null,system,stdout,stderr,file:<filename>]", settings.logging.sink, &settings.logging.sink);
        auto logfilterOption = op.add<Value<string>>(
            "", "logfilter", "Log filter <tag>:<level>[,<tag>:<level>]* with tag = * or <log tag> and level = [trace,debug,info,notice,warning,error,fatal]",
            settings.logging.filter);

        try
        {
            op.parse(argc, argv);
        }
        catch (const std::invalid_argument& e)
        {
            cerr << "Exception: " << e.what() << "\n";
            cout << "\n" << op << "\n";
            exit(EXIT_FAILURE);
        }

        if (versionSwitch->is_set())
        {
            cout << "snapclient v" << version::code << (!version::rev().empty() ? (" (rev " + version::rev(8) + ")") : ("")) << "\n"
                 << "Copyright (C) 2014-2025 BadAix (snapcast@badaix.de).\n"
                 << "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
                 << "This is free software: you are free to change and redistribute it.\n"
                 << "There is NO WARRANTY, to the extent permitted by law.\n\n"
                 << "Written by Johannes M. Pohl and contributors <https://github.com/badaix/snapcast/graphs/contributors>.\n\n";
            exit(EXIT_SUCCESS);
        }

        settings.player.player_name = utils::string::split_left(settings.player.player_name, ':', settings.player.parameter);

#if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI) || defined(HAS_PIPEWIRE)
        if (listSwitch->is_set())
        {
            try
            {
                vector<PcmDevice> pcm_devices;
#if defined(HAS_ALSA)
                if (settings.player.player_name == player::ALSA)
                    pcm_devices = AlsaPlayer::pcm_list();
#endif
#if defined(HAS_PULSE)
                if (settings.player.player_name == player::PULSE)
                    pcm_devices = PulsePlayer::pcm_list(settings.player.parameter);
#endif
#if defined(HAS_WASAPI)
                if (settings.player.player_name == player::WASAPI)
                    pcm_devices = WASAPIPlayer::pcm_list();
#endif
#if defined(HAS_PIPEWIRE)
                if (settings.player.player_name == player::PIPEWIRE)
                    pcm_devices = PipeWirePlayer::pcm_list(settings.player.parameter);
#endif
#ifdef WINDOWS
                // Set console code page to UTF-8 so console known how to interpret string data
                SetConsoleOutputCP(CP_UTF8);
                // Enable buffering to prevent VS from chopping up UTF-8 byte sequences
                setvbuf(stdout, nullptr, _IOFBF, 1000);
#endif
                for (const auto& dev : pcm_devices)
                    cout << dev.idx << ": " << dev.name << "\n" << dev.description << "\n\n";

                if (pcm_devices.empty())
                    cout << "No PCM device available for audio backend \"" << settings.player.player_name << "\"\n";
            }
            catch (const std::exception& e)
            {
                cout << "Failed to get device list: " << e.what() << "\n";
            }
            exit(EXIT_SUCCESS);
        }
#endif

        if (helpSwitch->is_set())
        {
            cout << op << "\n";
            exit(EXIT_SUCCESS);
        }

        if (groffSwitch->is_set())
        {
            GroffOptionPrinter option_printer(&op);
            cout << option_printer.print();
            exit(EXIT_SUCCESS);
        }

        settings.logging.filter = logfilterOption->value();
        if (logfilterOption->is_set())
        {
            for (size_t n = 1; n < logfilterOption->count(); ++n)
                settings.logging.filter += "," + logfilterOption->value(n);
        }

        if (settings.logging.sink.empty())
        {
            settings.logging.sink = "stdout";
#ifdef HAS_DAEMON
            if (daemonOption->is_set())
                settings.logging.sink = "system";
#endif
        }
        AixLog::Filter logfilter;
        auto filters = utils::string::split(settings.logging.filter, ',');
        for (const auto& filter : filters)
            logfilter.add_filter(filter);

        string logformat = "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)";
        if (settings.logging.sink.find("file:") != string::npos)
        {
            string logfile = settings.logging.sink.substr(settings.logging.sink.find(':') + 1);
            AixLog::Log::init<AixLog::SinkFile>(logfilter, logfile, logformat);
        }
        else if (settings.logging.sink == "stdout")
            AixLog::Log::init<AixLog::SinkCout>(logfilter, logformat);
        else if (settings.logging.sink == "stderr")
            AixLog::Log::init<AixLog::SinkCerr>(logfilter, logformat);
        else if (settings.logging.sink == "system")
            AixLog::Log::init<AixLog::SinkNative>("snapclient", logfilter);
        else if (settings.logging.sink == "null")
            AixLog::Log::init<AixLog::SinkNull>();
        else
            throw SnapException("Invalid log sink: " + settings.logging.sink);

        if (!op.unknown_options().empty())
        {
            throw SnapException("Unknown command line argument: '" + op.unknown_options().front() + "'");
        }

        if (deprecated_host_opt->is_set() || deprecated_port_opt->is_set())
        {
            LOG(WARNING, LOG_TAG) << "Options '--" << deprecated_host_opt->long_name() << "' and '--" << deprecated_port_opt->long_name()
                                  << "' are deprecated. Please add the server URI as last command line argument\n";
            settings.server.uri.host = deprecated_host_opt->value();
            settings.server.uri.port = deprecated_port_opt->value();
            settings.server.uri.scheme = "tcp";
        }

        if (!op.non_option_args().empty())
        {
            std::vector<std::string> schemes{"tcp", "ws"};
#ifdef HAS_OPENSSL
            schemes.emplace_back("wss");
#endif
            try
            {
                settings.server.uri.parse(op.non_option_args().front());
            }
            catch (...)
            {
                throw SnapException("Invalid URI - expected format: \"<scheme>://<host or IP>[:port]\", with 'scheme' one of: " +
                                    utils::string::container_to_string(schemes));
            }

            if (std::find(schemes.begin(), schemes.end(), settings.server.uri.scheme) == schemes.end())
                throw SnapException("Protocol must be one of: " + utils::string::container_to_string(schemes));

            if (!settings.server.uri.port.has_value())
            {
                if (settings.server.uri.scheme == "tcp")
                    settings.server.uri.port = 1704;
                else if (settings.server.uri.scheme == "ws")
                    settings.server.uri.port = 1780;
                else if (settings.server.uri.scheme == "wss")
                    settings.server.uri.port = 1788;
            }

            if (!settings.server.uri.user.empty() || !settings.server.uri.password.empty())
            {
                ClientSettings::Server::Auth auth;
                auth.scheme = "Basic";
                auth.param = base64_encode(settings.server.uri.user + ":" + settings.server.uri.password);
                settings.server.auth = auth;
            }
        }

        if (server_cert_opt->is_set())
        {
            if (server_cert_opt->get_default() == server_cert_opt->value())
                settings.server.server_certificate = "";
            else
                settings.server.server_certificate = std::filesystem::weakly_canonical(server_cert_opt->value());
            if (settings.server.server_certificate.value_or("").empty())
                LOG(INFO, LOG_TAG) << "Server certificate: default certificates\n";
            else
                LOG(INFO, LOG_TAG) << "Server certificate: " << settings.server.server_certificate.value_or("") << "\n";
        }

        if (!settings.server.certificate.empty() && !settings.server.certificate_key.empty())
        {
            namespace fs = std::filesystem;
            settings.server.certificate = fs::weakly_canonical(settings.server.certificate);
            if (!fs::exists(settings.server.certificate))
                throw SnapException("Certificate file not found: " + settings.server.certificate.string());
            settings.server.certificate_key = fs::weakly_canonical(settings.server.certificate_key);
            if (!fs::exists(settings.server.certificate_key))
                throw SnapException("Certificate_key file not found: " + settings.server.certificate_key.string());
        }
        else if (settings.server.certificate.empty() != settings.server.certificate_key.empty())
        {
            throw SnapException("Both SSL 'certificate' and 'certificate_key' must be set or empty");
        }

        if (settings.server.uri.host.empty())
        {
#ifndef HAS_MDNS
            throw SnapException("Snapserver host not configured and mDNS not available, please configure with \"--host\".");
#else
            LOG(INFO, LOG_TAG) << "No server URL given, defaulting to '" << default_uri << "'\n";
            settings.server.uri.parse(default_uri);
#endif
        }


#ifdef HAS_DAEMON
        std::unique_ptr<Daemon> daemon;
        if (daemonOption->is_set())
        {
            string pidFile = "/var/run/snapclient/pid";
            if (settings.instance != 1)
                pidFile += "." + cpt::to_string(settings.instance);
            string user;
            string group;

            if (userValue->is_set())
            {
                if (userValue->value().empty())
                    throw std::invalid_argument("user must not be empty");

                vector<string> user_group = utils::string::split(userValue->value(), ':');
                user = user_group[0];
                if (user_group.size() > 1)
                    group = user_group[1];
            }
            daemon = std::make_unique<Daemon>(user, group, pidFile);
            processPriority = std::min(std::max(-20, processPriority), 19);
            if (processPriority != 0)
                setpriority(PRIO_PROCESS, 0, processPriority);
            LOG(NOTICE, LOG_TAG) << "daemonizing\n";
            daemon->daemonize();
            LOG(NOTICE, LOG_TAG) << "daemon started\n";
        }
#endif

#ifdef HAS_SOXR
        if (sample_format->is_set())
        {
            settings.player.sample_format = SampleFormat(sample_format->value());
            if (settings.player.sample_format.channels() != 0)
                throw SnapException("sampleformat channels must be * (= same as the source)");
            auto bits = settings.player.sample_format.bits();
            if ((bits != 0) && (bits != 16) && (bits != 24) && (bits != 32))
                throw SnapException("sampleformat bits must be 16, 24, 32, * (= same as the source)");
        }
#endif

#if defined(HAS_OBOE) || defined(HAS_WASAPI)
        settings.player.sharing_mode = (sharing_mode->value() == "exclusive") ? ClientSettings::SharingMode::exclusive : ClientSettings::SharingMode::shared;
#endif

        if (settings.player.parameter == "?")
        {
            if (settings.player.player_name == player::FILE)
            {
                cout << "Options are a comma separated list of:\n"
                     << " \"filename=<filename>\" - with <filename> = \"stdout\", \"stderr\", \"null\" or a filename\n"
                     << " \"mode=[w|a]\" - w: write (discarding the content), a: append (keeping the content)\n";
            }
#ifdef HAS_PULSE
            else if (settings.player.player_name == player::PULSE)
            {
                cout << "Options are a comma separated list of:\n"
                     << " \"buffer_time=<buffer size [ms]>\" - default 100, min 10\n"
                     << " \"server=<PulseAudio server>\" - default not-set: use the default server\n"
                     << " \"property=<key>=<value>\" - can be set multiple times, default 'media.role=music'\n";
            }
#endif
#ifdef HAS_ALSA
            else if (settings.player.player_name == player::ALSA)
            {
                cout << "Options are a comma separated list of:\n"
                     << " \"buffer_time=<total buffer size [ms]>\" - default 80, min 10\n"
                     << " \"fragments=<number of buffers>\" - default 4, min 2\n";
            }
#endif
#ifdef HAS_PIPEWIRE
            else if (settings.player.player_name == player::PIPEWIRE)
            {
                cout << "Options are:\n"
                     << " \"buffer_time=<total buffer size [ms]>\" - default <not set, PipeWire will decide>, min 10\n";
            }
#endif
            else
            {
                cout << "No options available for \"" << settings.player.player_name << "\n";
            }
            exit(EXIT_SUCCESS);
        }

        settings.player.pcm_device = getPcmDevice(settings.player.player_name, settings.player.parameter, pcm_device);
#if defined(HAS_ALSA)
        if (settings.player.pcm_device.idx == -1)
        {
#if defined(HAS_PIPEWIRE)
            if (settings.player.player_name != player::PIPEWIRE)
#endif
                LOG(ERROR, LOG_TAG) << "PCM device \"" << pcm_device << "\" not found\n";
            // exit(EXIT_FAILURE);
        }
#endif

        string mode = utils::string::split_left(mixer_mode->value(), ':', settings.player.mixer.parameter);
        if (mode == "software")
            settings.player.mixer.mode = ClientSettings::Mixer::Mode::software;
        else if ((mode == "hardware") && hw_mixer_supported)
            settings.player.mixer.mode = ClientSettings::Mixer::Mode::hardware;
#ifdef SUPPORTS_VOLUME_SCRIPT
        else if (mode == "script")
            settings.player.mixer.mode = ClientSettings::Mixer::Mode::script;
#endif
        else if (mode == "none")
            settings.player.mixer.mode = ClientSettings::Mixer::Mode::none;
        else if ((mode == "?") || (mode == "help"))
        {
            cout << "mixer can be one of 'software', " << (hw_mixer_supported ? "'hardware', " : "")
#ifdef SUPPORTS_VOLUME_SCRIPT
                 << "'script', "
#endif
                 << "'none'\n"
                 << "followed by optional parameters:\n"
                 << " * software[:poly[:<exponent>]|exp[:<base>]]\n"
                 << (hw_mixer_supported ? " * hardware[:<mixer name>]\n" : "")
#ifdef SUPPORTS_VOLUME_SCRIPT
                 << " * script[:<script filename>]"
#endif
                 << "\n";
            exit(EXIT_SUCCESS);
        }
        else
            throw SnapException("Mixer mode not supported: " + mode);

        boost::asio::io_context io_context;
        // Construct a signal set registered for process termination.
        boost::asio::signal_set signals(io_context, SIGHUP, SIGINT, SIGTERM);
        signals.async_wait([&](const boost::system::error_code& ec, int signal)
        {
            if (!ec)
                LOG(INFO, LOG_TAG) << "Received signal " << signal << ": " << strsignal(signal) << "\n";
            else
                LOG(INFO, LOG_TAG) << "Failed to wait for signal, error: " << ec.message() << "\n";
            io_context.stop();
        });

        LOG(INFO, LOG_TAG) << "Version " << version::code << (!version::rev().empty() ? (", revision " + version::rev(8)) : ("")) << "\n";

        auto controller = make_shared<Controller>(io_context, settings);
        controller->start();

        int num_threads = 0;
        std::vector<std::thread> threads;
        threads.reserve(num_threads);
        for (int n = 0; n < num_threads; ++n)
            threads.emplace_back([&] { io_context.run(); });
        io_context.run();
        for (auto& t : threads)
            t.join();
    }
    catch (const std::exception& e)
    {
        LOG(FATAL, LOG_TAG) << "Exception: " << e.what() << "\n";
        exitcode = EXIT_FAILURE;
    }

    LOG(NOTICE, LOG_TAG) << "Snapclient terminated.\n";
    exit(exitcode);
}
