#!/bin/bash
set -x 
# General part ------------------------------------------
source /opt/scripts/mesh/freq.sh # get center frequency of channel like this: ${chan2g["1"]} 'OR' ${chan5g["149"]}
PHYNAME=$1
DEVNAME=$2
CHANNEL=${chan5g[$3]}
phy_number="${1//[!0-9]/}"
dev_number="${2//[!0-9]/}"
devPath="/sys/class/net/"
phyPath="/sys/kernel/debug/ieee80211/"

# check whether the phy exists
if [ -e "$phyPath$PHYNAME" ]; then
	echo "$PHYNAME exists in $phyPath, going on ..."
else
	echo "$PHYNAME do not exist in $phyPath, exit script ..."
	exit
fi

systemctl stop systemd-timesyncd.service

# check whether the wanted DEVNAME already exists and remove it
if [ -e "$devPath$DEVNAME" ]; then # if dev already exists
	number=$(iw dev "$DEVNAME" info | awk '$1 == "wiphy" {print $2}')
	echo "Removing existing device $DEVNAME from phy$number"
	ifconfig $DEVNAME down
	iw dev $DEVNAME del
fi

# get current dev on the specified phy
# delete any dev on specified phy
current_dev_on_phy=$(iw dev | awk -v phy="$phy_number" '$0 ~ "phy#"phy {getline; while ($1 ~ /^Interface/) {print $2; getline}}')
if [ ! -z "$current_dev_on_phy" ]; then
	echo "Removing existing device $current_dev_on_phy from phy$phy_number"
	ifconfig $current_dev_on_phy down
	iw dev $current_dev_on_phy del
fi

# creating the new dev 
# mesh_id is set to DEVNAME so that in case of init both phys they are in different mesh`s
echo "Creating new mesh device ${DEVNAME} on ${PHYNAME}"
iw phy ${PHYNAME} interface add ${DEVNAME} type mp mesh_id ${DEVNAME}

ifconfig ${DEVNAME} down 					# if interface was up

iw dev ${DEVNAME} set type mp				# set type mesh point
iw phy ${PHYNAME} set antenna 3 3			# ath9k/AR9280: OK (TX=3 RX=3)
iw phy ${PHYNAME} set retry short 7 long 4	# initialize adapter with default (re-)try limits
iw phy ${PHYNAME} set rts 500				# request to send (packet size threshold 500 octets/byte)
iw phy ${PHYNAME} set retry short 7 long 4	# initialize adapter with default (re-)try limits

iw dev ${DEVNAME} set power_save off		# deactivate power saving mechanism
ifconfig ${DEVNAME} up						# set interface up

iw dev ${DEVNAME} mesh leave
iw dev ${DEVNAME} mesh join mesh freq ${CHANNEL} HT40+ basic-rates 54 mcast-rate 54
iw dev ${DEVNAME} set txpower fixed 300 								# set tx power (300 eq 3dBm)
iw dev ${DEVNAME} set bitrates ht-mcs-5 6 sgi-5							# set coding scheme and guard interval (short for 5ghz -> 400ns)
echo 0 > /sys/kernel/debug/ieee80211/${PHYNAME}/ath9k/ani 				# set fixed noise floor in dBm
echo -110 > /sys/kernel/debug/ieee80211/${PHYNAME}/ath9k/nf_override	#TODO: overwritten individually below

# increase max. number of peer links to 50
#iw dev ${DEVNAME} set mesh_param mesh_max_peer_links=50

# automatically remove inactive links from station list
#iw dev ${DEVNAME} set mesh_param mesh_plink_timeout=20			# timeout in seconds

# Node specific part ------------------------------------------
# get the hostname
host_valid=0
nodename="$(uname -n)"
echo "Hostname: $nodename"
source /opt/scripts/mesh/node_addresses.sh
ALLNODES=${neighbors["all"]}

# check wheather hostname is valid
while [[ host_valid -eq 0 ]]; do
	for i in $ALLNODES; do
		if [[ $nodename == $i ]]; then
			host_valid=1
			echo "Hostname $nodename is valid"
			break
		fi
	done
	if [[ host_valid -eq 0 ]]; then
		sleep 1
		nodename="$(uname -n)"
	fi
done

# removing all IPs from dev
ip addr flush dev ${DEVNAME}

# get the dev corresponding IP
if [[ "$dev_number" -eq 0 ]]; then
	NODE_MESH_IP=${phy0IP["$nodename"]}
	BROADCAST_IP=${phy0IP["broadcast"]}
fi
if [[ "$dev_number" -eq 1 ]]; then
	NODE_MESH_IP=${phy1IP["$nodename"]}
	BROADCAST_IP=${phy1IP["broadcast"]}
fi
echo "The node mesh ip is: $NODE_MESH_IP"
ip -4 addr add ${NODE_MESH_IP}/24 broadcast $BROADCAST_IP dev ${DEVNAME}

source /opt/scripts/mesh/block_peer_links.sh

set +x