#!/bin/sh -v

# check arguments
if [ -z "$1" ] || [ -z "$2" ]
then
    echo "${0}: expected path to JSON and exclude.txt"
    exit 1
fi

# extract graph list
jq -c '.myGraphs[]' <"$1" >index.json

# remove according to exclude.txt
while read A
do
    sed -i "/${A}/d" index.json
done <"$2"

# convert timestamps to compact ordinal dates
#IFMT='%a, %d %b %Y %H:%M:%S GMT'
IFMT='%Y-%m-%dT%H:%M:%S'
OFMT='%Y-%jT%H:%M'
jq ".created = (.created | .[:19] | strptime(\"${IFMT}\") | strftime(\"${OFMT}\"))" <index.json >index2.json
mv index2.json index.json

# extract hash list
jq -r '.hash' <index.json >index.txt

# generate Markdown
~/perennial/desmos_archives/desmos-collection.jq <index.json >index.md

# copy PNGs, convert to JPG iff too big
while read A
do
    IMGPATH=`dirname "$1"`
    IMGPATH="${IMGPATH}/${A}.png"
    if [ -s "${A}.png" ] || [ -s "${A}.jpg" ]
    then
        continue
    fi
    if [ `stat -c '%s' "$IMGPATH"` -gt 32768 ]
    then
        magick "$IMGPATH" -quality 75 "${A}.jpg"
    else
        cp "$IMGPATH" "${A}.png"
    fi
done <index.txt

# replace references to .png with references to .jpg in Markdown
while read A
do
    if [ "${A%.png}" != "$A" ] && ! [ -f "$A" ]
    then
        echo "${A%.png}.jpg"
    else
        echo "$A"
    fi
done <index.md >>index2.md
mv index2.md index.md

# generate HTML
cat header.html >index.html
cmark --unsafe <index.md >>index.html
cat footer.html >>index.html
