#!/bin/bash

#
# ap-control.sh: script to scan captive portal network to enable or
# disable wifi on Aruba access point. Assume all of them having
# the same password.
#
# Use the ap-enable, ap-disable expect script distributed with fuss-server
#
# Usage: ap-control enable|disable [ ssh_pass ]
#
# To enable logging define: export LOGFILE=/path/to/log/file
#
# Copyright (C) 2019 FUSS Project <info@fuss.bz.it>
# Author: Simone Piccardi <piccardi@truelite.it>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

# Configuration and default variables
CPCONF=/etc/fuss-server/fuss-captive-portal.conf
APCONF=/etc/fuss-server/ap-config.sh
[ -n "$LOGFILE" ] || LOGFILE=/dev/null

# need captive portal configuration
if ! [ -f $CPCONF ]; then
    echo "Captive portal not configured, aborting."
    exit 1
fi
# get settings from AP config file if it exist
if [ -f $APCONF ]; then
    . $APCONF
fi
# getting values from parameters
ACTION=$1
if [ -n "$2" ]; then
    PASS=$2
fi

# ask password if not given on command line or config file
if [ -z "$PASS" ]; then
   echo -n Password: 
   read -s PASS
fi

# get default net value for AP from configuration
NET=$(sed -n -r 's/.*=(([0-9]+\.){3}).*/\1/p' $CPCONF)

# default values for AP ip range 
[ -n "AP_START" ] || AP_START=211
[ -n "AP_END" ] || AP_END=254

echo "Starting at $(date)" > $LOGFILE

for i in $(seq $AP_START $AP_END); do
   AP=${NET}${i}
   if ping -c1 -W1 $AP >> $LOGFILE; then
       echo Active AP at $AP
       case $ACTION in
         enable)
	       /usr/share/fuss-server/scripts/ap-enable $PASS $AP >> $LOGFILE
	   ;;
	 disable)
	       /usr/share/fuss-server/scripts/ap-disable $PASS $AP >> $LOGFILE
	   ;;
	 *)
	       echo "Usage: ap-control.sh enable|disable" 
	       exit 2
	       ;;
       esac
   fi
done
exit 0
