#!/bin/sh
#
# Start fpv datalink
#

. /etc/datalink.conf

chip=$(ipcinfo -c)
fw=$(grep "BUILD_OPTION" "/etc/os-release" | cut -d= -f2)

case "$1" in
  start)
	if ! [ -f /etc/system.ok ]; then
		killall majestic
		tweaksys ${chip}
	fi

	echo "Starting FPV datalink..."

	if [ ${fw} = "lte" ]; then
	  if [ ${usb_modem} = "true" ]; then
		echo "Starting lte modem configuration..."
		echo "ToDo: Running usb_modeswitch or other shit here..."
	  fi
	  # for the future
	  #cli -s .outgoing.url1 udp://${gs_ipaddr}:${gs_port}
	  if [ ${use_zt} = "true" ]; then
		echo "Starting ZeroTier-One daemon..."
		/usr/sbin/zerotier-one -d &
		if [ ! -f /var/lib/zerotier-one/networks.d/${zt_netid}.conf ]; then
		  sleep 8
		  zerotier-cli join ${zt_netid} &> /dev/null
		  echo "Don't forget authorize in the my.zerotier.com!"
		fi
	  fi
	  if [ ${telemetry} = "true" ]; then
		/usr/bin/telemetry start
	  fi
	else
	  echo "Starting wifibroadcast service..."
	  /usr/bin/wifibroadcast start
	fi
	;;
  stop)
    echo "Stopping all services..."
    kill -9 $(pidof wfb_tx)
    kill -9 $(pidof telemetry_rx)
    kill -9 $(pidof telemetry_tx)
    kill -9 $(pidof mavlink-routerd)
    kill -9 $(pidof mavfwd)
	;;
    *)
    echo "Usage: $0 {start|stop}"
    exit 1
esac