#!/bin/sh
#
# Start wifibroadcast
#

. /etc/wfb.conf

keydir="/etc"
chip=$(ipcinfo -c)

driver=""

# "0bda:8813" -> (8814) -> 8814au
# "0846:9052" -> (8811) -> 8821au

detect_wifi_card() {
  echo "Detecting wifi card vendor..."
  devices=$(lsusb | cut -d ' ' -f6 | sort | uniq)
  for card in ${devices}
	do
	  case "${card}" in
	  "0bda:8812" | "0bda:881a" | "0b05:17d2" | "2357:0101")
		driver="realtek"
		modprobe 88XXau rtw_tx_pwr_idx_override=${driver_txpower_override}
	  ;;
	  "0cf3:9271")
		driver="atheros"
		modprobe mac80211
		modprobe ath9k_htc
	  ;;
	  "148f:3070")
		driver="ralink"
		modprobe mac80211
		modprobe rt2x00usb
		modprobe rt2800usb
	  ;;
	esac
  done

  if [ -z "${driver}" ]; then
	echo "No usb wifi card detected. Check wifi stick connection, usb power or possible bad soldering."
	exit
  else
	echo "Detected:" ${driver}
  fi

  echo "Awaiting interface ${wlan} in system..."

  local n=0
  while ! $(ifconfig -a | grep -q ${wlan})
  do
	if [ ${n} -ge 5 ]; then
	  echo "No interface ${wlan}. Check wifi stick connection, usb power or possible bad soldering."
	  exit
	fi
	sleep 0.5
	n=$(expr ${n} + 1)
  done
}

load_modules() {
  modprobe cfg80211
  detect_wifi_card
}

load_interface() {
  if [ ${driver} = "realtek" ]; then
	  ifconfig ${wlan} up
	  iwconfig ${wlan} mode monitor
  elif [ ${driver} = "atheros" ] || [ ${driver} = "ralink" ]; then
	  iwconfig ${wlan} mode monitor
	  ifconfig ${wlan} up
  fi

  iw reg set ${region}
  iwconfig ${wlan} channel ${channel}
  iw dev ${wlan} set txpower fixed $((${txpower} * 100))
}

start_wfb() {
  wfb_tx -p ${stream} -u ${udp_port} -K ${keydir}/drone.key -B ${bandwidth} -M ${mcs_index} -S ${stbc} -L ${ldpc} -G ${guard_interval} -k ${fec_k} -n ${fec_n} -T ${fec_timeout} -i ${link_id} ${wlan} &
}

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

    if [ ${daemon} -eq 1 ]; then

	  echo "Loading modules and wifi card driver..."

	  load_modules

	  echo "Preparing interface wlan..."
	  
	  load_interface
	  
	  if ! cat ${keydir}/drone.key > /dev/null 2>&1; then
		echo "Generating drone & ground station keys..."
		cd ${keydir} ; wfb_keygen
	  else
		echo "Drone key exist..."
	  fi

	  echo "Starting Wifibroadcast service..."
	  
	  start_wfb

	  echo "Done."

	  if [ ${telemetry} = "true" ]; then
		if [ ${chip} = "gk7205v200" ]; then
			# UART2_RX mux
			devmem 0x120c0010 32 0x1e04
		fi
		/usr/bin/telemetry start
	  fi

	else
      echo "Wifibroadcast service disabled in wfb.conf..."
	fi
    ;;
  stop)
    echo "Stopping wifibroadcast service..."
    kill -9 $(pidof wfb_tx)
    ;;
    *)
    echo "Usage: $0 {start|stop}"
    exit 1
esac