#!/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")

# Namen der Zwischenergebnis Dateien
JSON_POS="${FILENAME}_positionsdraw.json"
JSON_TODRAW="${FILENAME}_todraw.json"
# Namen der Ergebnisdateien
ERROR_DOUBLE="${FILENAME}_errors.json"
EXCEL_RES="${FILENAME}_cables.xlsx"
DXF_RES="${FILENAME}_cables.dxf"

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

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_BOM_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
echo "=== Creating Graph for Routing ==="
"$SCRIPT_DIR/routing.sh" --filename "$JSON_POS" -w "$JSON_TODRAW"

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

echo
echo "=== Writing Output Files ==="
"$SCRIPT_DIR/draw_dxf.sh" --filename "$JSON_TODRAW" --new "$DXF_RES" -x "$EXCEL_RES"

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

echo

mkdir -p "$PROJECT_BOM_RESULTS/$FILENAME"
mv "$PROJECT_WORK/${FILENAME}_"* "$PROJECT_BOM_RESULTS/$FILENAME"
read -p "Press any key to continue..."

