#!/bin/bash
# Lineageos workaround for Samsung Galaxy s4-mini (i9195) sporadically losing
# mobile network
# 
# Principle of operation:
# 
# Periodically run a script that verifies the output of "getprop gsm.sim.state"
# and if it is not "LOADED", kill qmuxd. 
# 
# The sytem will restart qmuxd and this makes the SIM working again.
# 
# The watchdog script will be placed in /data/root/sim_watchdog.sh
# 
# cron will be set up to run on the system and root's crontab placed in /data/crontab/root
# configured to run the watchdog script every 10 minutes.
# (in practice, cron on Android does not run the script quite as regularly;
# still it usually runs a couple times per hour, which is OK)
# 
# Each time qmuxd is killed, this will be logged in /sdcard/qmuxd-watchdog-kills.txt
# 
# 1) root the phone using Magisk
# 
# 2) install BusyBox 
# (https://play.google.com/store/apps/details?id=stericson.busybox&hl=en&gl=US)
# 
# 3) run bash bash and in it run these commands (or just run this file)

mount -o remount,rw /

#create the watchdog script
mkdir /data/root
cat <<"_EOF" > /data/root/sim_watchdog.sh
#!/system/bin/sh
STATE=$(getprop gsm.sim.state)
if [[ $STATE != LOADED ]]; then
        killall qmuxd
        date "+%Y-%m-%d %H:%M:%S  SIM state: $STATE, restarting qmuxd" >> /sdcard/qmuxd-watchdog-kills.txt
fi

_EOF
chmod a+x /data/root/sim_watchdog.sh


# make root user known to cron
echo 'root:x:0:0:root:/data:/system/bin/sh' > /system/etc/passwd 

# create root crontab
mkdir /data/crontab
echo '*/10 * * * * /data/root/sim_watchdog.sh' > /data/crontab/root

# start crond on boot
cat > /etc/init/cron.rc <<_EOF 
service crond /system/xbin/crond -f -c /data/crontab
    class late_start
    user root
    group root system
    seclabel u:r:magisk:s0
_EOF

mount -o remount,ro /


