// 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 <cstdlib>
#include <cstring>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#include <buildboxcommon_notify.h>

namespace buildboxcommon {

void systemd_notify_socket_send_ready()
{
    auto path = getenv("NOTIFY_SOCKET");
    if (!path)
        return;

    struct sockaddr_un un = {};
    un.sun_family = AF_UNIX;

    strncpy(un.sun_path, path, sizeof(un.sun_path) - 1);
    if (un.sun_path[0] == '@')
        un.sun_path[0] = 0;

    int fd = socket(AF_UNIX, SOCK_DGRAM, 0);
    if (fd < 0)
        return;

    auto data = "READY=1";

    ssize_t ret = sendto(
        fd, data, strlen(data), 0,
        reinterpret_cast< // NOLINT
                          // (cppcoreguidelines-pro-type-reinterpret-cast)
            sockaddr *>(&un),
        static_cast<socklen_t>(offsetof(struct sockaddr_un, sun_path) +
                               strlen(path)));
    (void)ret;

    close(fd);
}

} // namespace buildboxcommon
