/**************************************************************************

Copyright (c) 2004-17 Simon Peter
Portions Copyright (c) 2010 RazZziel

All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

**************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libgen.h>
#include <dirent.h>
#include <string.h>

#define die(...)                                    \
    do {                                            \
        fprintf(stderr, "Error: " __VA_ARGS__);     \
        exit(1);                                    \
    } while(0);
#define MAX(a,b)    (a > b ? a : b)
#define bool int
#define false 0
#define true -1

#define LINE_SIZE 255

int filter(const struct dirent *dir) {
    char *p = (char*) &dir->d_name;
    p = strrchr(p, '.');
    return p && !strcmp(p, ".desktop");
}

int main(int argc, char *argv[]) {
    char *appdir = dirname(realpath("/proc/self/exe", NULL));
    if (!appdir)
        die("Could not access /proc/self/exe\n");

    int ret;
    struct dirent **namelist;
    ret = scandir(appdir, &namelist, filter, NULL);

    if (ret == 0) {
        die("No .desktop files found\n");
    } else if(ret == -1) {
        die("Could not scan directory %s\n", appdir);
    }

    /* Extract executable from .desktop file */
    char *desktop_file = malloc(LINE_SIZE);
    snprintf(desktop_file, LINE_SIZE-1, "%s/%s", appdir, namelist[0]->d_name);
    FILE *f     = fopen(desktop_file, "r");
    char *line  = malloc(LINE_SIZE);
    char *exe   = line+5;
    size_t n    = LINE_SIZE;

    do {
        if (getline(&line, &n, f) == -1)
            die("Executable not found, make sure there is a line starting with 'Exec='\n");
    } while(strncmp(line, "Exec=", 5));
    fclose(f);

    // parse arguments
    bool in_quotes = 0;
    for (n = 0; n < LINE_SIZE; n++) {
        if (!line[n])         // end of starting
            break;
        else if (line[n] == 10 || line[n] == 13) {
            line[n] = '\0';
            line[n+1] = '\0';
            line[n+2] = '\0';
            break;
        } else if (line[n] == '"') {
            in_quotes = !in_quotes;
        } else if (line[n] == ' ' && !in_quotes)
            line[n] = '\0';
    }

    // count arguments
    char*   arg         = exe;
    int     argcount    = 0;
    while ((arg += (strlen(arg)+1)) && *arg)
        argcount += 1;

    // merge args
    char*   outargptrs[argcount + argc + 1];
    outargptrs[0] = exe;
    int     outargindex = 1;
    arg                 = exe;
    int     argc_       = argc - 1;     // argv[0] is the filename
    char**  argv_       = argv + 1;
    while ((arg += (strlen(arg)+1)) && *arg) {
        if (arg[0] == '%' || (arg[0] == '"' && arg[1] == '%')) {         // handle desktop file field codes
            char code = arg[arg[0] == '%' ? 1 : 2];
            switch(code) {
                case 'f':
                case 'u':
                    if (argc_ > 0) {
                        outargptrs[outargindex++] = *argv_++;
                        argc_--;
                    }
                    break;
                case 'F':
                case 'U':
                    while (argc_ > 0) {
                        outargptrs[outargindex++] = *argv_++;
                        argc_--;
                    }
                    break;
                case 'i':
                case 'c':
                case 'k':
                    fprintf(stderr, "WARNING: Desktop file field code %%%c is not currently supported\n", code);
                    break;
                default:
                    fprintf(stderr, "WARNING: Invalid desktop file field code %%%c\n", code);
                    break;
            }
        } else {
            outargptrs[outargindex++] = arg;
        }
    }
    while (argc_ > 0) {
        outargptrs[outargindex++] = *argv_++;
        argc_--;
    }
    outargptrs[outargindex] = '\0';     // trailing null argument required by execvp()

    // change directory
    char usr_in_appdir[1024];
    sprintf(usr_in_appdir, "%s/usr", appdir);
    ret = chdir(usr_in_appdir);
    if (ret != 0)
        die("Could not cd into %s\n", usr_in_appdir);

    // set environment variables
    char *old_env;
    const int LENGTH = 2047;
    char new_env[8][LENGTH+1];

    /* https://docs.python.org/2/using/cmdline.html#envvar-PYTHONHOME */
    snprintf(new_env[0], LENGTH, "PYTHONHOME=%s/usr/", appdir);

    int a,b;
    old_env = getenv("PATH") ?: "";
    snprintf(new_env[1], LENGTH, "PATH=%1$s/usr/bin/:%1$s/usr/sbin/:%1$s/usr/games/:%1$s/bin/:%1$s/sbin/:%2$s", appdir, old_env);

    old_env = getenv("LD_LIBRARY_PATH") ?: "";
    snprintf(new_env[2], LENGTH, "LD_LIBRARY_PATH=%1$s/usr/lib/:%1$s/usr/lib/i386-linux-gnu/:%1$s/usr/lib/x86_64-linux-gnu/:%1$s/usr/lib/x86_64-linux-gnu/samba:%1$s/usr/lib/x86_64-linux-gnu/vdpau:%1$s/usr/lib/x86_64-linux-gnu/dri:%1$s/usr/lib32/:%1$s/usr/lib64/:%1$s/lib/:%1$s/lib/i386-linux-gnu/:%1$s/lib/x86_64-linux-gnu/:%1$s/lib32/:%1$s/lib64/:%2$s", appdir, old_env);

    old_env = getenv("XDG_DATA_DIRS") ?: "";
    snprintf(new_env[3], LENGTH, "XDG_DATA_DIRS=%s/usr/share/:%s", appdir, old_env);

    /* http://askubuntu.com/questions/251712/how-can-i-install-a-gsettings-schema-without-root-privileges */
    old_env = getenv("GSETTINGS_SCHEMA_DIR") ?: "";
    snprintf(new_env[4], LENGTH, "GSETTINGS_SCHEMA_DIR=%s/usr/share/glib-2.0/schemas/:%s", appdir, old_env);

    old_env = getenv("QT_PLUGIN_PATH") ?: "";
    snprintf(new_env[5], LENGTH, "QT_PLUGIN_PATH=%1$s/lib/python3/dist-packages/PyQt5/Qt/:%1$s/usr/lib/qt5/plugins/:%1$s/usr/lib/i386-linux-gnu/qt5/plugins/:%1$s/usr/lib/x86_64-linux-gnu/qt5/plugins/:%1$s/usr/lib32/qt5/plugins/:%1$s/usr/lib64/qt5/plugins/:%2$s", appdir, old_env);

    snprintf(new_env[6], LENGTH, "QT_APPIMAGE=%s", "1");
    snprintf(new_env[7], LENGTH, "NO_AT_BRIDGE=%s", "1");

    for (n = 0; n < 8; n++)
        putenv(new_env[n]);

    /* Run */
    ret = execvp(exe, outargptrs);

    if (ret == -1)
        die("Error executing '%s'; return code: %d\n", exe, ret);

    free(line);
    free(desktop_file);
    return 0;
}
