This has been hell to figure out. Might as well put it out here to help anyone else googling around.
For the Samsung Galaxy S7, first the script:
#!/system/bin/sh
# Script to reboot the system as soon as the charger is inserted
# https://android.googlesource.com/kernel/common/+/android-trusty-3.10/Documentation/sysrq.txt
# Enable kernel commands.
su -c "echo 1 > /proc/sys/kernel/sysrq"
# Send an immediate reboot request.
echo b > /proc/sysrq-trigger
And to install it, you first backup and replace the /system/bin/lpm file.
As OP already mentioned, replacing the file will cause it not to work (explained here)
The inode (file unique identifier) of the lpm file has to remain the same before Android will accept it, so instead we have to replace the contents of the existing file.
That's easily enough done:
echo /system/bin/lpm > /system/bin/lpm.bak
And dump our script code into it:
echo /sdcard/reboot_on_charge.sh > /system/bin/lpm
Of course this will require root, and to remount the system folder as read-write:
su
mount -o rw,remount /system
And that's it! That's how I got this to work for the S7.
Undoing the changes should be as simple as doing:
cat /system/bin/lpm.bak > /system/bin/lpm
rm /system/bin/lpm.bak
Edit:
- To add an extra detail, make sure the file is using Linux (LF) line endings as opposed to CR_LF (Windows). My git repo switched them out from under me and I was left debugging why the phone suddenly started going to recovery mode again when it reboots.