#define _POSIX_C_SOURCE 200809L

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv){
    (void)argc;

    char executable[PATH_MAX];
    const ssize_t length = readlink("/proc/self/exe", executable,
                                    sizeof(executable) - 1);
    if(length <= 0){
        fprintf(stderr, "[launcher] cannot resolve executable path: %s\n",
                strerror(errno));
        return 126;
    }
    executable[length] = '\0';

    char *slash = strrchr(executable, '/');
    if(!slash){
        fprintf(stderr, "[launcher] invalid executable path: %s\n", executable);
        return 126;
    }
    *slash = '\0';

    char library_path[PATH_MAX];
    if(snprintf(library_path, sizeof(library_path), "%s/lib", executable) >=
       (int)sizeof(library_path)){
        fprintf(stderr, "[launcher] library path is too long\n");
        return 126;
    }
    const char *old_library_path = getenv("LD_LIBRARY_PATH");
    if(old_library_path && *old_library_path){
        const size_t used = strlen(library_path);
        if(snprintf(library_path + used, sizeof(library_path) - used,
                    ":%s", old_library_path) >=
           (int)(sizeof(library_path) - used)){
            fprintf(stderr, "[launcher] LD_LIBRARY_PATH is too long\n");
            return 126;
        }
    }
    if(setenv("LD_LIBRARY_PATH", library_path, 1) != 0){
        fprintf(stderr, "[launcher] cannot set library path: %s\n",
                strerror(errno));
        return 126;
    }

    char core_path[PATH_MAX];
    if(snprintf(core_path, sizeof(core_path), "%s/webrtcpush-core", executable) >=
       (int)sizeof(core_path)){
        fprintf(stderr, "[launcher] core path is too long\n");
        return 126;
    }
    argv[0] = core_path;
    execv(core_path, argv);
    fprintf(stderr, "[launcher] cannot start %s: %s\n",
            core_path, strerror(errno));
    return 126;
}
