#!/bin/bash

#
# This script generates a data structure that tells which fonts are available and
# which unicode characters they support.
#

if [ -f gen_once/fontlist.hh -o -f gen_once/fontlist.cc ]; then
    echo ""
    echo "ERROR:  gen_once/fontlist.hh or gen_once/fontlist.cc already exists."
    echo ""
    echo "Delete the old ones before new can be created."
    echo ""
    exit 20
fi

mkdir -p gen_once

FONTS=`ls /usr/share/fonts/truetype/noto/NotoSans*Regular.ttf /usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc`

echo fonts are
for file in $FONTS; do echo $file; done

#
# Want shortest font names first -- they are likely the most normal.  So sort them by name length
#

FONTS_SORTED_BY_LENGTH=`(for name in $FONTS; do echo $name; done) | awk '{ print length(), $0 | "sort -n" }' | sed 's/^[0-9]*[ ]*//; s/[ ]*$//'`

echo fonts sorted by length are

for file in $FONTS_SORTED_BY_LENGTH; do echo $file; done

#
# Here can limit the number, for testing.
#
#FONTS_SORTED_BY_LENGTH=`for file in $FONTS_SORTED_BY_LENGTH; do echo $file; done | head -3`


FONTS_TO_USE=`for file in $FONTS_SORTED_BY_LENGTH; do echo $file; done; echo /usr/share/fonts/truetype/noto/NotoColorEmoji.ttf`

echo "fonts for generating header file (with emojis) are"

for file in $FONTS_TO_USE; do echo $file; done



#
# Here we build the header file
#

cat >gen_once/fontlist.hh <<EOF
#ifndef FONTLIST_HH
#define FONTLIST_HH


struct start_end
{
  const char32_t start;
  const char32_t end;
};

struct font
{
  const char*              name;
  const struct start_end*  codes;
  struct FT_FaceRec_**     face;
  int                      height;
  int                      bitmap_height;
};

extern font fontlist[];

#endif
EOF


cat >gen_once/fontlist.cc <<EOF

#include "fontlist.hh"

EOF

for file in $FONTS_TO_USE; do

    font_no_extension=`basename $file | sed 's/[.].*//; s/[^a-zA-Z0-9]/_/g'`
    cat >>gen_once/fontlist.cc <<EOF

const start_end codes_for_font_${font_no_extension}[] =
{
EOF

    echo "Processing font file $file."
    exe/check_font_symbol_range $file >>gen_once/fontlist.cc;

    cat >>gen_once/fontlist.cc <<EOF
};
EOF
done


cat >>gen_once/fontlist.cc <<EOF



font fontlist[] =
{
EOF

for file in $FONTS_TO_USE; do
    font_no_extension=`basename $file | sed 's/[.].*//; s/[^a-zA-Z0-9]/_/g'`
    cat >>gen_once/fontlist.cc <<EOF
  {
    .name    =  "$file",
    .codes   =  codes_for_font_$font_no_extension,
    .face    =  0,
    .height  =  0
  },
EOF
done

cat >>gen_once/fontlist.cc <<EOF
  {
    .name    =  0,
    .codes   =  0,
    .face    =  0,
    .height  =  0
  },
};
EOF
