#! /bin/bash
set -e # exit immediately upon error(s)

# Infer location of the clafer model directory.
SCRIPT_DIR=$(dirname -- "$(readlink -f -- "$0")")
CLAFER_DIR=$(dirname -- "$SCRIPT_DIR")

# Enter clafer model directory (parent folder of 'scripts).
cd $CLAFER_DIR

# Input and output Clafer files.
INPUT_FILE="e2eviv.cfr"
OUTPUT_FILE1="e2eviv_skinned.cfr"
OUTPUT_FILE2="e2eviv_skinned_opt.cfr"

# Note that sed is slightly differently parametrized on macOS.
if [ "$(uname -s)" == "Darwin" ]; then
  SED_OPTS="-i .backup"
else
  SED_OPTS="-i"
fi

# Copy INPUT_FILE to OUTPUT_FILE1 (only the latter we modify).
cp "$INPUT_FILE" "$OUTPUT_FILE1"

# Remove label, name and description fields from clafers.
sed $SED_OPTS -- 's#label -> string#// label -> string#' "$OUTPUT_FILE1"
sed $SED_OPTS -- 's#name -> string#// name -> string#' "$OUTPUT_FILE1"
sed $SED_OPTS -- 's#description -> string#// description -> string#' "$OUTPUT_FILE1"

# Remove label, name and description constraints everywhere.
sed $SED_OPTS -- '/label = /d'       "$OUTPUT_FILE1"
sed $SED_OPTS -- '/name = /d'        "$OUTPUT_FILE1"
sed $SED_OPTS -- '/description = /d' "$OUTPUT_FILE1"

# Copy OUTPUT_FILE1 to OUTPUT_FILE2 (only the latter we modify).
cp "$OUTPUT_FILE1" "$OUTPUT_FILE2"

# Remove '// [ENABLE_WHEN_OPT] ' prefix at the start of line.
sed $SED_OPTS -- 's#^[ \t]*//[ \t]*\[ENABLE_WHEN_OPT\][ \t]*##' "$OUTPUT_FILE2"

# Remove .backup files generated by macOS sed.
rm -f "$OUTPUT_FILE1.backup"
rm -f "$OUTPUT_FILE2.backup"
