#!/bin/bash

# Hostapd launch helper script.
#
# It allows for previously defined settings to be used as variables.
# Also it is possible to use bash command substition and other bash operations.
# It also makes sure that all interfaces and bss's attached to a bridge
# have the same 'pvid untagged' as the bridge's self port.

HOSTAPD="/usr/sbin/hostapd"
#HOSTAPD="/root/hostap/hostapd/hostapd"
HCONFPATH="/etc/hostapd"
OUTPATH="/run/hostapdconf"

device="hostapd"
pidfile=""
while [[ "$#" -gt 1 ]]; do
    case $1 in
        -p|--pidfile) pidfile="$2"; shift ;;
        -d|--device) device="$2"; shift ;;
        -b|--bool) bool=1 ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done
if [ -z $pidfile ]; then
  [ $device -eq "hostapd" ] && pidfile=/run/hostapd.pid \
                            || pidfile=/run/hostapd.$device.pid
fi

post=0

mkdir -p $OUTPATH
bss=""
infile=$HCONFPATH"/"$device".conf"
outfile=$OUTPATH"/"$device".conf"
echo "# Generated by hostapd-launch" >$outfile
GLOBIGNORE="*"
readarray -t filearray < $infile
for (( i=0; i<${#filearray[@]}; i++ ))
do
  line=${filearray[i]}         
  if [[ $line == "" ]]; then echo >>$outfile; continue; fi   # Empty line
  if [[ ${line:0:1} == '#'  ]]; then continue; fi    # Remove comment lines
  line=${line%%#*}           # Remove comment in line
  line=${line/"\\"/"\\\\"}   # Replace \ with \\ to save \ from the next command
  line=${line@P}             # Expand variables mentioned in the line
  declare "$line"            # declare and take care of spaces
  case $line in 
    bridge_vlan=*)           # Should be in .conf before bridge=
      ;;
    bridge=*)
      [[ $bss == "" ]] && bss=$interface
      execpost[post]="addvlan $bss ${line/bridge=/} $bridge_vlan"
      ((post++))
      echo $line >>$outfile
      ;;
    interface=*)
      while [ ! -d /sys/class/net/$interface ]; do sleep 0.1; done
      echo $line >>$outfile
      ;;
    *) 
      echo $line >>$outfile
      ;;
  esac
done
unset GLOBIGNORE

echo Running: $HOSTAPD -B -P $pidfile $DAEMON_OPTS $outfile
$HOSTAPD -B -P $pidfile $DAEMON_OPTS $outfile

function addvlan { 
  while [ ! -d /sys/class/net/$1/brport ]; do sleep 0.1; done
  vlanfilt=$(cat /sys/class/net/$2/bridge/vlan_filtering)
  if [ $vlanfilt == 1 ]; then
    if [ -z "$3" ]; then
      vlanid=($(bridge vlan show dev $2 | grep $2 | grep PVID))
      vlanid=${vlanid[1]}
    else
      vlanid=$3
    fi
    echo "Adding dev $1 to vid $vlanid"
    bridge vlan add dev $1 vid $vlanid pvid untagged
  fi
};

if [[ $? == 0 ]]; then
  for (( i=0; i<$post; i++ )); do
    ${execpost[i]}      
  done
fi

exit 0
