#!/bin/sh

kill_cell_service()
{
    service sigcell stop
    count=`ps aux | grep cell_service | grep -v grep | wc -l`

    iter=0
    while [ $count -ne 0 -a $iter -lt 60 ]; do
	    sleep 1
	    let iter=iter+1 > /dev/null
	    count=`ps aux | grep cell_service | grep -v grep | wc -l`
    done

    if [ $count -ne 0 ] ; then
        killall -KILL cell_service
    fi
}

kill_packet_forwarder()
{
    service signetik stop
    count=`ps aux | grep lora_pkt_fwd | grep -v grep | wc -l`

    iter=0
    while [ $count -ne 0 -a $iter -lt 60 ]; do
	    sleep 1
	    let iter=iter+1 > /dev/null
	    count=`ps aux | grep lora_pkt_fwd | grep -v grep | wc -l`
    done

    if [ $count -ne 0 ] ; then
        killall -KILL lora_pkt_fwd
    fi
}

kill_packet_forwarder
kill_cell_service

if [ -e /var/siggate.bin -o -e /root/siggate.bin -o -e /tmp/siggate.bin ]; then

    mount -o rw /
    if ! pkg info siggate >/dev/null 2>&1; then
        rm -f /var/db/pkg/local.sqlite
    fi
    if [ -e /tmp/siggate.bin ]; then
        pkg add -f /tmp/siggate.bin
        rm /tmp/siggate.bin
    fi
    if [ -e /root/siggate.bin ]; then
        pkg add -f /root/siggate.bin
        rm /root/siggate.bin
    fi
    if [ -e /var/siggate.bin ]; then
        pkg add -f /var/siggate.bin
        rm /var/siggate.bin
    fi
    mount -o ro /
fi

service sigcell start
service signetik start
