#!/bin/bash

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

    Converts output from various dump files into a format which can be used by
    Crafting Guide.  BEFORE RUNNING THIS SCRIPT, YOU MUST FIRST CREATE THE
    NECESSARY DUMP FILES.

    First, set up your Minecraft profile with the mod you want to dump as well
    as NEI and MineTweaker 3.  Then, launch the game into a single player world
    and run the following console commands:

        /mt oredict
        /mt recipes
        /mt recipes furnace

    Then, open your inventory and click the "NEI Subsets" button at the top.
    Right-click the "Mod" menu, and then left-click the one mod you want to
    dump.  This should change the icons displayed on the right to just those
    belonging to that mod.

    Now, click the "Options" button in the lower-right corner. Then click
    "Tools" followed by "Data Dumps". Next to "Item Panel", click the center
    button until it says "PNG" and then the left hand button until it says
    "48x48".  Finally, click the "Dump" button.

    Next, click the center button on the "Item Panel" row until it says "CSV",
    and then click "Dump" again.

    You have now created all the dump files needed by this script.

    <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

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

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

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
