#!/bin/sh

# Download CSV from https://datahub.io/core/language-codes
FILE="language-codes-full.csv"

tail -n +2 $FILE | \
gawk -F , -v OFS=',' -vFPAT='[^,]*|"[^"]*"' '{ printf "%s,%s,%s,%s\n", $4, $1, $2, $3 }' | sort | gawk -F , -v OFS=',' -vFPAT='[^,]*|"[^"]*"' '{ printf "%s,%s,%s,%s\n", $2, $3, $4, $1 }' > language-codes-sorted.csv

FILE="language-codes-sorted.csv"

echo "#ifndef GAVL_LANGUAGE_TABLE_H"
echo "#define GAVL_LANGUAGE_TABLE_H"

echo "// Generated by utils/make_language_table.sh"

echo "static const struct\n"
echo "  {"
echo "  const char * ISO_639_2_B;"
echo "  const char * ISO_639_2_T;"
echo "  const char * ISO_639_1;"
echo "  const char * label;"
echo "  }"
echo "languages[] ="
echo "  {"

gawk -F , -v OFS=',' -vFPAT='[^,]*|"[^"]*"' 'length($1) == 3 { printf "    { \"%s\", ", $1; if($2 == "") printf "NULL, "; else printf "\"%s\", ", $2; if($3 == "") printf "NULL, "; else printf "\"%s\", ", $3; if(!match($4, "\"")) printf "\"%s\" },\n", $4; else printf "%s },\n", $4;  }' $FILE

echo "  };"

echo "#endif // GAVL_LANGUAGE_TABLE_H"
