#!/bin/bash

set -e

APP="$1"

if [[ -z "$APP" ]]; then
  echo "Usage: $0 /path/to/App.app"
  exit 1
fi

if [[ ! -d "$APP" ]]; then
  echo "Error: '$APP' is not a valid .app bundle"
  exit 1
fi

PLIST="$APP/Contents/Info.plist"

if [[ ! -f "$PLIST" ]]; then
  echo "Error: Info.plist not found"
  exit 1
fi

# Generate a random bundle ID
UUID=$(uuidgen | tr 'A-Z' 'a-z')
BUNDLE_ID="com.random.${UUID}"

echo "Setting bundle identifier to: $BUNDLE_ID"

# Update CFBundleIdentifier
/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier $BUNDLE_ID" "$PLIST" 2>/dev/null || \
/usr/libexec/PlistBuddy -c "Add :CFBundleIdentifier string $BUNDLE_ID" "$PLIST"

# Re-sign the app (ad-hoc)
echo "Re-signing app..."
codesign --deep --force --sign - "$APP"

# Clear extended attributes
echo "Clearing extended attributes..."
xattr -cr "$APP"

echo "Done."
