#!/bin/bash

usage() {
    echo "Usage: $0 <dxfinWorkOrdner.dxf>"
    exit 1
}

if [ $# -eq 0 ]; then
    usage
fi

INPUT_FILE="$1"
FILENAME=$(basename "$INPUT_FILE" .dxf)
DIR=$(dirname "$INPUT_FILE")

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/setenv.sh"

# Namen der Zwischenergebnis Dateien
JSON_POS="${FILENAME}_positionsconv.json"
JSON_TODRAW="${FILENAME}_todraw.json"
# Namen der Ergebnisdateien
ERROR_DOUBLE="${FILENAME}_errors.json"
RESULT_TIA="${FILENAME}-*_TIA.xlsx"

echo
echo "=== Fetching Positions ==="
"$SCRIPT_DIR/getpositions.sh" --filename "$1" -s -r -w "$JSON_POS" -e "$ERROR_DOUBLE"

if [ -f "$PROJECT_WORK/$ERROR_DOUBLE" ]; then
    echo "== failed: duplicate IDs in given layout"
    read -p "Press any key to continue..."
    mv "$PROJECT_WORK/$ERROR_DOUBLE" "$PROJECT_IO_RESULTS"
    exit 1
fi

if [ ! -f "$PROJECT_WORK/$JSON_POS" ]; then
    echo "== failed: getpositions"
    read -p "Press any key to continue..."
    exit 1
fi

echo "=== Creating Excel Files for TIA, WSCAD, .. ==="
"$SCRIPT_DIR/portalexport.sh" --filename "$JSON_POS" --outname "$FILENAME"

if [ ! -f "$PROJECT_WORK/$RESULT_TIA" ]; then
    echo "== failed: creating .xlsx files"
    read -p "Press any key to continue..."
    exit 1
fi

mkdir -p "$PROJECT_IO_RESULTS/$FILENAME"
echo "move $PROJECT_WORK/${FILENAME}-* $PROJECT_IO_RESULTS/$FILENAME"
mv "$PROJECT_WORK/${FILENAME}"-* "$PROJECT_IO_RESULTS/$FILENAME"
read -p "Press any key to continue..."
