#!/usr/bin/env bash
# =============================================================================
# build-and-patch.sh — build the Mono.Cecil patcher and patch the Flex API
# license gate in one shot.
#
# Usage:
#   ./build-and-patch.sh [path-to-OpenOptions.dnaFusion.Flex.Common.dll] [softkey]
#
# Defaults:
#   dll     = <script dir>/../../OpenOptions.dnaFusion.Flex.Common.dll
#   softkey = FLEXSTUB
#
# The script builds PatchLicense.cs into a throwaway dotnet project, runs it
# against the target DLL (backing it up to <dll>.orig first), and prints a
# summary. Restart the Flex service afterwards.
# =============================================================================
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOY="$(cd "$HERE/../.." && pwd)"

DLL="${1:-$DEPLOY/OpenOptions.dnaFusion.Flex.Common.dll}"
SOFTKEY="${2:-FLEXSTUB}"

if [[ ! -f "$DLL" ]]; then
  echo "ERROR: target DLL not found: $DLL" >&2
  exit 2
fi

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

echo ">> Scaffolding patcher project in $WORK"
cd "$WORK"
dotnet new console -o patcher -n PatchLicense >/dev/null
cp "$HERE/PatchLicense.cs" patcher/Program.cs
cd patcher
dotnet add package Mono.Cecil >/dev/null

echo ">> Building patcher"
dotnet build -v q >/dev/null

echo ">> Patching $DLL (softkey=$SOFTKEY)"
dotnet run --no-build -- "$DLL" "$SOFTKEY"

echo
echo "Done. Restart the Flex service to apply."
