#!/bin/bash
if [ ! -f $1.sb2 ] ; then
  echo "syntax: $0 ubuntumono"
  echo "        - requires ubuntumono.sb2 to have been created with fonts.py"
  exit 1
fi
cat <<EOF > trans.c
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE 1024

int main(int argc, char **argv) {
  static char *s, line[MAX_LINE+1], comment[MAX_LINE+1];
  int count, x, y, r, g, b;
  for (;;) {
    s = fgets(line, MAX_LINE, stdin);
    if (s == NULL) break;
    count = sscanf(line, "# ImageMagick pixel enumeration: %d,%d,%d,rgb\\n", &r, &g, &b);
    if (count == 3) {
      fprintf(stdout, "# ImageMagick pixel enumeration: %d,%d,%d,rgba\\n", r, g, b);
    } else {
      count = sscanf(line, "%d,%d: (%d,%d,%d)  #%s\\n", &x, &y, &r, &g, &b, comment);
      if (count == 6) {
        if (r == 0 && g == 255 && b == 0) { // background
          fprintf(stdout, "%d,%d: (0,0,0,0)  #%s\\n", x, y, comment);
	} else {
          fprintf(stdout, "%d,%d: (255,0,0,%d)  #%s\\n", x, y, r, comment);
	}
      } else {
        fputs(line, stdout);
      }
    }
  }
  exit(EXIT_SUCCESS);
  return (EXIT_FAILURE);
}
EOF
cc -o trans trans.c
mkdir $1 2> /dev/null
cd $1
unzip -o ../$1.sb2
mkdir temp 2> /dev/null
for glyph in `ls -1 *.png |grep -v "^0.png$" ` ; do
  echo "../trans $glyph > temp/$glyph"
  sh -c "convert $glyph txt:- | ../trans | convert - temp/$glyph"
  befores="`md5sum $glyph`"
  afters="`md5sum temp/$glyph`"
  before=($befores)
  after=($afters)
  echo "sed -i 's/${before[0]}/${after[0]}/' project.json"
  sed -i 's/${before[0]}/${after[0]}/' project.json
  mv temp/$glyph $glyph
  chmod 777 $glyph
done
rm -rf temp
zip -r ../$1 *
cd ..
mv $1.zip $1-trans.sb2
if [ -d $1 ] ; then
  rm -rf $1
fi
