#!/bin/sh
set -eu

ROOT="$(cd "$(dirname "$0")" && pwd)"
BUILD_DIR="${SIRIPLUS_REMOTE_MIC_BUILD_DIR:-$ROOT/build}"
DRIVER="$BUILD_DIR/SiriPlusRemoteMic.driver"
MACOS_DIR="$DRIVER/Contents/MacOS"
INFO_PLIST="$ROOT/Info.plist"
if [ ! -f "$INFO_PLIST" ]; then
  INFO_PLIST="$ROOT/DriverInfo.plist"
fi
SOURCE_FILE="$ROOT/src/SiriPlusRemoteMic.c"
if [ ! -f "$SOURCE_FILE" ]; then
  SOURCE_FILE="$ROOT/SiriPlusRemoteMic.c"
fi
if [ -z "${SIRIPLUS_REMOTE_MIC_BUILD_DIR:-}" ] && [ ! -f "$ROOT/Info.plist" ]; then
  TMP_ROOT="${TMPDIR:-/tmp}"
  BUILD_DIR="$(/usr/bin/mktemp -d "${TMP_ROOT%/}/SiriPlusRemoteMicDriver-build.XXXXXX")"
  DRIVER="$BUILD_DIR/SiriPlusRemoteMic.driver"
  MACOS_DIR="$DRIVER/Contents/MacOS"
fi

if ! /bin/rm -rf "$DRIVER" 2>/dev/null; then
  if [ -n "${SIRIPLUS_REMOTE_MIC_BUILD_DIR:-}" ]; then
    echo "Could not remove driver build output at $DRIVER" >&2
    exit 1
  fi

  TMP_ROOT="${TMPDIR:-/tmp}"
  BUILD_DIR="$(/usr/bin/mktemp -d "${TMP_ROOT%/}/SiriPlusRemoteMicDriver-build.XXXXXX")"
  DRIVER="$BUILD_DIR/SiriPlusRemoteMic.driver"
  MACOS_DIR="$DRIVER/Contents/MacOS"
  echo "Default driver build output is not writable; using $BUILD_DIR" >&2
fi

mkdir -p "$MACOS_DIR"
TOOL_TMP_DIR="$BUILD_DIR/tool-tmp"
mkdir -p "$TOOL_TMP_DIR"
TMPDIR="$TOOL_TMP_DIR"
TEMP="$TOOL_TMP_DIR"
TMP="$TOOL_TMP_DIR"
export TMPDIR TEMP TMP
cp "$INFO_PLIST" "$DRIVER/Contents/Info.plist"

SOURCE_SIZE="$(/usr/bin/wc -c < "$SOURCE_FILE" | /usr/bin/tr -d '[:space:]')"
INFO_SIZE="$(/usr/bin/wc -c < "$INFO_PLIST" | /usr/bin/tr -d '[:space:]')"
SOURCE_HASH="$(
  {
    /usr/bin/printf 'SiriPlusRemoteMicDriverIdentity:content-v3\nSiriPlusRemoteMic.c:%s\n' "$SOURCE_SIZE"
    /bin/cat "$SOURCE_FILE"
    /usr/bin/printf '\nInfo.plist:%s\n' "$INFO_SIZE"
    /bin/cat "$INFO_PLIST"
  } | /usr/bin/shasum -a 256 | /usr/bin/awk '{print $1}'
)"
BUILT_AT="$(/bin/date -u +"%Y-%m-%dT%H:%M:%SZ")"

xcrun clang \
  -Wall \
  -Wextra \
  -Werror \
  -std=c11 \
  -fblocks \
  -fPIC \
  -bundle \
  "$SOURCE_FILE" \
  -framework CoreAudio \
  -framework CoreFoundation \
  -o "$MACOS_DIR/SiriPlusRemoteMic"

/usr/libexec/PlistBuddy -c "Set :SiriPlusDriverSourceSHA256 $SOURCE_HASH" "$DRIVER/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Set :SiriPlusDriverIdentityVersion content-v3" "$DRIVER/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Set :SiriPlusDriverBuiltAt $BUILT_AT" "$DRIVER/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Delete :SiriPlusDriverBinarySHA256" "$DRIVER/Contents/Info.plist" 2>/dev/null || true

codesign --force --options runtime --sign - "$DRIVER"
BINARY_HASH="$(/usr/bin/shasum -a 256 "$MACOS_DIR/SiriPlusRemoteMic" | /usr/bin/awk '{print $1}')"

echo "SiriPlusRemoteMic source $SOURCE_HASH"
echo "SiriPlusRemoteMic binary $BINARY_HASH"
echo "$DRIVER"
