#!/bin/bash

read -d '' USAGE <<END
USAGE: convert-nei-dump <source> <mod_slug> <mod_version>

    Converts output from NEI dump files into a format which can be used by
    Crafting Guide. In particlar, this script looks for the "Item Panel" dump
    both in PNG and CSV formats and assumes they contain all the data for the
    target mod.

    Unfortunate, NEI doesn't generate enough information to fill in all the
    recipes for each item: only their names. Once this script has converted the
    data, you will need to manually enter the missing content.

    <source>      :    the "dumps" directory where NEI dropped its content
    <mod_slug>    :    the slug of the mod being converted
    <mod_version> : the version of the mod being converted
END


SOURCE_DIR="$1"; shift
MOD_SLUG="$1"; shift
MOD_VERSION="$1"; shift

mkdir -p "./data/$MOD_SLUG/versions/$MOD_VERSION"
DATA_FILE="./data/$MOD_SLUG/versions/$MOD_VERSION/mod-version.cg"

if [[ "$SOURCE_DIR" == "" || "$MOD_SLUG" == "" || "$MOD_VERSION" == "" ]]; then
    echo "$USAGE"
    exit 1
fi

if [[ ! -e "$DATA_FILE" ]]; then
    echo "schema: 1" > $DATA_FILE
    echo "" >> $DATA_FILE
fi

ls $SOURCE_DIR/itempanel_icons | while read FILE; do
    ITEM_NAME="$(echo $FILE | sed 's/.png//')"
    ITEM_SLUG="$(echo $ITEM_NAME \
        | sed 's/[^a-zA-Z0-9]/_/g' \
        | sed 's/__*/_/g' \
        | sed 's/^_//' \
        | sed 's/_$//' \
        | tr '[A-Z]' '[a-z]' \
    )"
    mkdir -p "./data/$MOD_SLUG/items/$ITEM_SLUG"
    cp "$SOURCE_DIR/itempanel_icons/$FILE" "./data/$MOD_SLUG/items/$ITEM_SLUG/icon.png"
    if ! grep -q "item: $ITEM_NAME$" $DATA_FILE; then
        echo "# item: $ITEM_NAME" >> $DATA_FILE
        echo "#    recipe:" >> $DATA_FILE
        echo "#        input:" >> $DATA_FILE
        echo "#        pattern: ... ... ..." >> $DATA_FILE
        echo "#        quantity: 1" >> $DATA_FILE
        echo "#        tools: Crafting Table" >> $DATA_FILE
        echo "" >> $DATA_FILE
    fi
done
