/*
 *   mytest.c - simple test for iso-codes
 *
 *   author: Philippe Baril Lecavalier
 *   This was prepared for testing the package iso-codes on Cygwin. It should
 *   work as is elsewhere.
 *
 */


#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "gettext.h"
#include "iconv.h"
#include "libintl.h"

/*
 *
 * perform tests, given data in csv file

while IFS=, read -r from to iso lang;
do
    ./mytest "${from}" "${to}" "${iso}" "${lang}"
done < test-data.csv

 *
 * generate translated messages given csv:

while IFS=, read -r from to iso lang;
do
    ./mytest -p  "${from}" "." "${iso}" "${lang}" >> test-data-new.csv
done < test-data.csv

 *
 */

void help(void)
{
    puts("usage: mytest [OPTION] str1 str2 iso lang\n"
    "\n"
    "   optional:\n"
    "   -d  path to locales (default: /usr/share/locales)\n"
    "   -p  print only lookup results (value of input str2 is discarded)\n"
    "\n"
    "   mandatory: 4 arguments - THERE ARE FOUR LIGHTS\n"
    "   str1  original string to translate\n"
    "   str2  translated string\n"
    "   iso   iso code to lookup\n"
    "   lang  language code\n"
    "\n"
    "example: mytest \"French\" \"Français\" \"iso_639-2\" \"fr_CA.UTF-8\"\n"
    "quotes are optional, unless string has a space\n"
    );
}


int main (int argc, char **argv)
{
    char *path = "/usr/share/locale/";
    int c;
    bool printonly=false;

    opterr = 0;

    while ((c = getopt(argc, argv, "pd:")) != -1)
    switch (c)
    {
        case 'd': // directory with locales
                  // default: /usr/share/locale
            path = optarg;
            break;
        case 'p':  // print only result (ignore second argument)
            printonly = true;
            break;
        case '?':
            help();
            return 1;
        default:
            abort ();
    }

    if ((argc - optind) != 4)
    {
        help();
        return 1;
    }

    char const *str1 = argv[optind++];
    char const *str2 = argv[optind++];
    char const *iso  = argv[optind++];
    char const *lang = argv[optind++];
    char *tellme;

    setlocale(LC_ALL, lang);
    setenv("LC_ALL", lang, 1);
    setenv("LANG", lang, 1);

    textdomain(iso);
    bindtextdomain(iso, path);
    tellme = dgettext(iso, str1);

    if (printonly) {
        printf("%s,%s,%s,%s\n", str1, tellme, iso, lang);
        return 0;
    }

    if (strcmp(str2, tellme) == 0) {
        printf("%s, %s:\n    %s -> %s .. ok\n\n", lang, iso, str1, tellme);
        return 0;
    }
    else {
        printf("%s, %s:\n    %s -> %s .. no\n", lang, iso, str1, tellme);
        printf("\033[32;1m    expected: %s\n\033[0m"
               "\033[31;1m    obtained: %s\n\n\033[0m", str2, tellme);
        return 1;
    }

    return 0;
}

// gcc -std=gnu99 -O2 -Wall -Wno-unused-result -I /usr/share/gettext/ -DHAVE_ICONV=1 -DENABLE_NLS=1 -DHAVE_GETTEXT=1 -DHAVE_DCGETTEXT=1 -o mytest mytest.c -lintl
