#!/bin/sh
. /tmp/loader
BASTIAN="00:21:6a:32:7c:1c"		# X301

case "$CONFIG_PROFILE" in
	*ap)
		CHECK_DEV="wlan0"
	;;
	*hybrid)
		CHECK_DEV="wlan0"
	;;
esac

log()
{
	logger -s "$(date) $@"
}

while true; do {
	iw dev "$CHECK_DEV" station dump |
	 while read LINE; do {
		case "$LINE" in
			"Station"*)
				set -- $LINE
				MAC="$2"
			;;
			*"tx failed:"*)
				set -- $LINE
				V1="txf: $3"
			;;
			*"signal:"*)
				set -- $LINE
				V2="sig: $2"

				case "$MAC" in
					"$BASTIAN")
						LINE="$LINE ***"
					;;
				esac

				if [ -e "/tmp/known_mac.$MAC" ]; then
					:
				else
					touch "/tmp/known_mac.$MAC"
					log "[new player] $MAC"
				fi

				if [ $2 -lt -60 ]; then
					if [ -e "/tmp/prepare_kick.$MAC" ]; then
						read UP REST </proc/uptime; UP=${UP%.*}
						NEXT_ALLOWED_KICK=$UP
						[ -e "/tmp/allow_kick.$MAC" ] && read NEXT_ALLOWED_KICK <"/tmp/allow_kick.$MAC"

						if [ $NEXT_ALLOWED_KICK -le $UP ]; then
							log "[roaming-force] $MAC: $V1 $V2"
							echo "$(( $UP + 30 ))" >"/tmp/allow_kick.$MAC"
							rm "/tmp/known_mac.$MAC"
							ubus call "hostapd.$CHECK_DEV" del_client "{ \"addr\" : \"$MAC\", \"reason\" : \"assoc toomany\" }"
						else
							log "[roaming_not_allowed] $MAC: $V1 $V2"
						fi
					else
						log "[getting worse] Station $MAC: $V1 $V2"
						touch "/tmp/prepare_kick.$MAC"
					fi
				else
					[ $2 -gt 0 ] && log "[oops,int>0] $LINE"
#					log "[OK] Station $MAC: $V1 $V2"
					[ -e "/tmp/prepare_kick.$MAC" ] && rm "/tmp/prepare_kick.$MAC"
				fi
			;;
		esac
	} done
	sleep 1
} done
