#!/usr/bin/env bash

command -v jq >/dev/null 2>&1 || { echo >&2 "I require jq (json parser) but it's not installed. Aborting."; exit 1; }

CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
BASE_DIR="$(dirname "${CURRENT_DIR}")"

DATA_FILE="${CURRENT_DIR}/data.json"
touch "${DATA_FILE}"

# backup current file
# NOW="$(date '+%Y%m%d_%H%M%S')"
# cp "${DATA_FILE}" "${DATA_FILE}.bak_${NOW}.json"

cd "${CURRENT_DIR}"
php manage_data.php "${DATA_FILE}"

# format json file
cat "${DATA_FILE}" | jq >"${DATA_FILE}.tmp"
mv "${DATA_FILE}.tmp" "${DATA_FILE}"

# inject json file in app code
GAME_DATA_DART_FILE="${BASE_DIR}/lib/data/game_data.dart"
echo "class GameData {" >"${GAME_DATA_DART_FILE}"
echo "  static const Map<String, dynamic> data = $(cat "${DATA_FILE}");" >>"${GAME_DATA_DART_FILE}"
echo "}" >>"${GAME_DATA_DART_FILE}"

# cat "${DATA_FILE}"