#!/bin/bash

# Util for generating .h file from html fils for ESP8266 Device Hive firmware

set -e

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

TARGETFILE="$DIR/pages.h"

print() {
  echo "$@" >> $TARGETFILE
}

echo "/* This is autogenerated file. Do not modify directly. */" > $TARGETFILE
print "#ifndef _PAGES_H_"
print "#define _PAGES_H_"
print '#include "../sources/irom.h"'
print "typedef struct {const char *path; const char *data; unsigned int data_len;} WEBPAGE;"

index="WEBPAGE web_pages[] = { "
comma=""
FILE_LIST=$(find $DIR -name \*.html -o -name \*.css -o -name \*.js)
FILE_LIST="$FILE_LIST $DIR/favicon.ico"
for file in $FILE_LIST; do
    filename=$(basename "$file")
    echo "Parsing $filename ..."
    name=${filename/./_}
    data=$(gzip -c $file | od -An -v -t x1 | tr -d '\n' | sed -E "s/( +)([[:xdigit:]]{2})/\\\x\2/g")
    print "RO_DATA char $name[] = \"$data\";"
    index="$index$comma {\"$filename\", $name, sizeof($name) - 1}"
    comma=", "
done
print "$index };"
print "#endif /* _PAGES_H_ */"
echo "$(basename $TARGETFILE) successfully generated."
