#!/usr/bin/env bash
set -Eeuo pipefail

EXPECTED_HOST="armoros"
REPO="/home/shire3d/ARMOR"
SOURCE_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TARGET="$REPO/tools/flexiforge"
LAUNCHER="$REPO/bin/shire-flexiforge"
BACKUP_ROOT="/SHiREVault/Backup/OSBackups"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP_DIR="$BACKUP_ROOT/FLEXIFORGE-SHIRE-INTEGRATION-$STAMP"

fail(){ echo "FLEXIFORGE INSTALL STOP: $1" >&2; exit 1; }

[[ "$(hostname)" == "$EXPECTED_HOST" ]] || fail "Wrong host. Expected $EXPECTED_HOST."
[[ -d "$REPO/.git" ]] || fail "ARMOR repository not found at $REPO."
cd "$REPO"
[[ -z "$(git status --porcelain)" ]] || fail "ARMOR repository is not clean."
[[ -e /SHiREVault ]] || fail "SHiREVault is unavailable. No local fallback is permitted."
REAL_VAULT="$(readlink -f /SHiREVault)"
MOUNT="$(findmnt -T "$REAL_VAULT" -no TARGET 2>/dev/null || true)"
[[ -n "$MOUNT" && "$MOUNT" != "/" ]] || fail "SHiREVault is not on a verified network mount."
mkdir -p "$BACKUP_DIR"
[[ -w "$BACKUP_DIR" ]] || fail "Backup destination is not writable: $BACKUP_DIR"

git bundle create "$BACKUP_DIR/ARMOR-pre-flexiforge.bundle" --all
git bundle verify "$BACKUP_DIR/ARMOR-pre-flexiforge.bundle" >/dev/null
printf '%s\n' "Network backup verified before FlexiForge integration." > "$BACKUP_DIR/README.txt"

[[ ! -e "$TARGET" ]] || fail "$TARGET already exists; refusing to overwrite."
mkdir -p "$(dirname "$TARGET")" "$(dirname "$LAUNCHER")"
cp -a "$SOURCE_ROOT" "$TARGET"
cat > "$LAUNCHER" <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail
ROOT="/home/shire3d/ARMOR/tools/flexiforge"
[[ -x "$ROOT/.venv/bin/python" ]] || { echo "FlexiForge venv is not prepared. Run $ROOT/start_linux.sh once." >&2; exit 1; }
exec "$ROOT/.venv/bin/python" "$ROOT/shire_flexiforge.py" "$@"
EOF
chmod +x "$LAUNCHER" "$TARGET/start_linux.sh"

cat <<EOF
FlexiForge SHiRE integration candidate installed.
Target: $TARGET
Launcher: $LAUNCHER
Backup: $BACKUP_DIR
No service was enabled, no BlenderMCP files were touched, and no Git commit was made.
EOF
