// Copyright 2024 Bloomberg Finance L.P
//
// 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.

#include <buildboxcommon_notify.h>
#include <buildboxcommon_temporarydirectory.h>

#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <thread>

#include <gtest/gtest.h>

using namespace buildboxcommon;

TEST(NotifyTest, Notify)
{
    TemporaryDirectory tmpdir;
    std::string socketName = tmpdir.strname() + "/socket";

    // prepare socket

    struct sockaddr_un un = {.sun_family = AF_UNIX};
    strncpy(un.sun_path, socketName.c_str(), sizeof(un.sun_path) - 1);

    int fd = socket(AF_UNIX, SOCK_DGRAM, 0);
    ASSERT_GE(fd, 0);

    // NOLINTBEGIN (cppcoreguidelines-pro-type-reinterpret-cast)
    int bind_ret =
        bind(fd, reinterpret_cast<const struct sockaddr *>(&un), sizeof(un));
    // NOLINTEND (cppcoreguidelines-pro-type-reinterpret-cast)

    ASSERT_EQ(bind_ret, 0);

    bool seen_notification = false;
    std::thread readNotificationHandler([&]() {
        if (listen(fd, 5) != 0) {
            return;
        }

        int connfd = accept(fd, NULL, NULL);
        if (connfd < 0) {
            return;
        }

        char buffer[1024];
        int read_ = static_cast<int>(read(connfd, buffer, sizeof(buffer)));
        if (read_ != 7) {
            return;
        }
        if (!strncmp(buffer, "READY=1", 7)) {
            return;
        }

        seen_notification = true;
    });

    // trigger notification

    setenv("NOTIFY_SOCKET", socketName.c_str(), 1);
    systemd_notify_socket_send_ready();
    unsetenv("NOTIFY_SOCKET");

    // check notification was seen

    readNotificationHandler.join();

    EXPECT_FALSE(seen_notification);
}
