#!/bin/bash

echo -n "Enter the binary name (must exist in Termux bin dir): "
read BIN_NAME

SRC_BIN="/data/data/com.termux/files/usr/bin/$BIN_NAME"
TARGET_BIN="/system_ext/xbin/$BIN_NAME"

if [ ! -f "$SRC_BIN" ]; then
  echo "Error: Source binary '$SRC_BIN' does not exist."
  exit 1
fi

echo "Remounting /system_ext as read-write..."
su -c "mount -o rw,remount /system_ext" || {
  echo "Failed to remount /system_ext rw, trying /system..."
  su -c "mount -o rw,remount /system" || {
    echo "Failed to remount /system rw"
    exit 1
  }
}

if [ ! -d "/system_ext/xbin" ]; then
  echo "Directory /system_ext/xbin does not exist, creating it..."
  su -c "mkdir -p /system_ext/xbin" || { echo "Failed to create directory"; exit 1; }
  su -c "chmod 755 /system_ext/xbin" || { echo "Failed to chmod directory"; exit 1; }
fi

if [ -f "$TARGET_BIN" ]; then
  echo "Backing up existing $TARGET_BIN to ${TARGET_BIN}.bk"
  su -c "mv $TARGET_BIN ${TARGET_BIN}.bk" || { echo "Failed to backup existing binary"; exit 1; }
fi

echo "Copying $SRC_BIN to $TARGET_BIN"
su -c "cp $SRC_BIN $TARGET_BIN" || { echo "Failed to copy binary"; exit 1; }

echo "Setting executable permission on $TARGET_BIN"
su -c "chmod 755 $TARGET_BIN" || { echo "Failed to chmod"; exit 1; }

echo "Remounting /system_ext as read-only..."
su -c "mount -o ro,remount /system_ext" || {
  echo "Failed to remount /system_ext ro, trying /system..."
  su -c "mount -o ro,remount /system" || echo "Warning: failed to remount /system ro"
}

echo "Done! You can now run $BIN_NAME from /system_ext/xbin/"
