#!/bin/bash

set -e

if test "$1" != start -a "$1" != stop; then
    die "Usage: $(basename $0) [start|stop]"
fi

if test "$1" = start -o "$1" = on; then
    touch /data/do-current-rftx
    logwrapper bash -x -c '
    tcmd-at at+cmee=2 # AT error should be human readable.
    tcmd-at at+cfun=1
    tcmd-at "at*band=4"
    for x in $(seq 1 10); do
        tcmd-at "at+creg?" | grep -q "CREG:.*0" || break
        usleep 500000
    done

    while test -e /data/do-current-rftx; do
        tcmd-at "atd112;" "NO CARRIER"
    done
    ' >/dev/null 2>&1 &
else
    rm /data/do-current-rftx || true
    killall tcmd-at || true
    tcmd-at at+cfun=0 || true
    true
fi
    
