#!/system/bin/sh
MODDIR="${0%/*}"

OVERLAY_UPPER=/mnt/.cswp_overlay
OVERLAY_WORK=/mnt/.cswp_work
OVERLAY_WORK_ETC=/mnt/.cswp_work_etc

# Clean any stale workdir state from previous mounts. OverlayFS workdirs MUST be
# pristine — if left dirty after a lazy umount (umount -l), the kernel gets confused.
rm -rf "$OVERLAY_WORK" "$OVERLAY_WORK_ETC"
mkdir -p "$OVERLAY_WORK" "$OVERLAY_WORK_ETC"
mkdir -p "$OVERLAY_UPPER/system/priv-app/CamSwapper"
mkdir -p "$OVERLAY_UPPER/system/etc/permissions"

# Copy APK and privapp permissions XML to overlay upper dir.
# Android 16 requires privileged permission allowlisting — without the privapp XML,
# system_server FATAL EXCEPTION crashes on boot.
cp "$MODDIR/system/priv-app/CamSwapper/CamSwapper.apk" \
   "$OVERLAY_UPPER/system/priv-app/CamSwapper/"
cp "$MODDIR/system/etc/permissions/privapp-permissions-camswapper.xml" \
   "$OVERLAY_UPPER/system/etc/permissions/"

# Set permissions and SELinux context
chmod 755 "$OVERLAY_UPPER/system/priv-app/CamSwapper"
chmod 644 "$OVERLAY_UPPER/system/priv-app/CamSwapper/CamSwapper.apk"
chmod 644 "$OVERLAY_UPPER/system/etc/permissions/privapp-permissions-camswapper.xml"
chcon -R u:object_r:system_file:s0 "$OVERLAY_UPPER/system"

# Mount overlay on /system/priv-app so PackageManager sees CamSwapper as priv-app
mount -t overlay overlay \
  -o lowerdir=/system/priv-app,upperdir="$OVERLAY_UPPER/system/priv-app",workdir="$OVERLAY_WORK" \
  /system/priv-app

# Mount overlay on /system/etc/permissions with its own workdir so SystemConfig
# finds the privapp permissions XML during early boot.
mkdir -p "$OVERLAY_WORK_ETC"
mount -t overlay overlay \
  -o lowerdir=/system/etc/permissions,upperdir="$OVERLAY_UPPER/system/etc/permissions",workdir="$OVERLAY_WORK_ETC" \
  /system/etc/permissions
