#!/bin/bash

adaptor=$(ip addr | grep wlan1)
NOW=$(date +"%m-%d-%y-%H%M%S")

# Make sure we have correct settings in /etc/kismet/kismet.conf
sed -i 's/log_prefix=.\//log_prefix=\/captures\/kismet\//g' /etc/kismet/kismet_logging.conf
sed -i '0,/# source=wlan0/s//source=wlan1/' /etc/kismet/kismet.conf
sed -i 's/# gps=gpsd:host=localhost,port=2947/gps=gpsd:host=localhost,port=2947/g' /etc/kismet/kismet.conf

f_check_dbus(){
if DBUS=$(pgrep dbus)
then
        echo "Dbus is running: $DBUS"
else
        echo "Dbus is not running. Staring..."
        service dbus start
fi
}


f_checkwlan1(){

if [ -z "$adaptor" ]; then # First check for wlan 1
    echo "Attempting to bring wlan1 up" # Still not seeing wlan 1, try again
    ifconfig wlan1 up # Not up, so bring it
    sleep 2
    if [ -z "$adaptor" ]; then
        echo "Still not detecting wlan1, please try plugging it in again."
        sleep 5
        clear
        echo -e "\e[31mWLAN1: NOT FOUND\e[0m"
        echo ""
        read -p "Press any key to exit..."
        exit
    fi
else
    echo -e "\e[92mWLAN1: FOUND\e[0m"
fi

}

f_kismet(){
    kismet -t Kismet-$NOW; --use-gpsd-gps # -t = Title of logfile
}

f_kismetdb_to_kml(){
    clear
    # export kml of all wireless data and copy files to sdcard
kismetdb_to_kml --in /captures/kismet/Kismet-$NOW.kismet --out "/captures/kismet/Kismet-$NOW.kml"
}

f_kismet_save(){

echo "Detected kali-nh capture folder, moving capture files"
mkdir -p /sdcard/captures
cd /sdcard/captures
zip -rj "kismet-captures-$NOW.zip" /captures/kismet/Kismet-$NOW*
echo "Successfully copied to /sdcard/captures/kismet-captures-$NOW.zip"
sleep 3

# option to erase files
read -p "Would you like to secure erase all Kismet session files in /captures folder inside chroot? (y/n): " ERASEKISMET
if [ "$ERASEKISMET" == "y" ]; then
    echo "Removing capture files..."
    wipe -f -i -r /captures/kismet/Kismet-$NOW*
fi
}

f_cleanup(){
pkill gpsd
pkill socat
rm -f /tmp/gps_out
rm -f /tmp/gps
}

sleep 5

#  She packed my bags last night pre-flight
#  Zero hour nine a.m.

f_check_dbus
f_checkwlan1

#  And I think it's gonna be a long long time...

f_kismet
f_kismetdb_to_kml
f_kismet_save

# Till touch down brings me round again to find

f_cleanup
