#!/mod/bin/jimsh

source /mod/webif/lib/setup
require system.class

httpheader "application/json"

if {![system has wifi_dongle]} {
	puts "\[]"
	exit
}

catch {exec ifconfig wlan0 up}
if {[catch {set op [exec /mod/bin/iwlist wlan0 scan]}]} {
	puts "\[]"
	exit
}

set lines [split $op "\n"]

puts "\["
set cur 0
foreach line [split $op "\n"] {
	set extra [lassign [split $line :] key val]
	switch -glob [string trim $key] {
	    *Address {
		if {$cur} {
			if {![llength $authtypes]} {
				lappend authtypes "WEP"
			}
			puts ","
			puts "    \"auth\": \"$authtypes\""
			puts "  \},"
		} else {
			incr cur
		}
		set authtypes {}
		puts "  \{"
		set mac "$val:[join $extra :]"
		puts -nonewline "    \"address\": \"[string trim $mac]\""
	    }
	    IE {
		switch -glob [string trim $val] {
		    "WPA Version 1" {
			lappend authtypes "WPA/"
		    }
		    *WPA2* {
			lappend authtypes "WPA2/"
		    }
		}
	    }
	    "Group Cipher" {
		switch -glob [string trim $val] {
		    TKIP {
			set x [lindex $authtypes end]
			append x "TKIP"
			lset authtypes end $x
		    }
		    CCMP {
			set x [lindex $authtypes end]
			append x "AES"
			lset authtypes end $x
		    }
		}
	    }
	    "Pairwise Ciphers*" {
		switch -glob [string trim $val] {
		    *TKIP* {
			set x [lindex $authtypes end]
			if {![string match *TKIP* $x]} {
				if {![string match */ $x]} {
					append x +
				}
				append x "TKIP"
			}
			lset authtypes end $x
		    }
		    *CCMP* {
			set x [lindex $authtypes end]
			if {![string match *AES* $x]} {
				if {![string match */ $x]} {
					append x +
				}
				append x "AES"
			}
			lset authtypes end $x
		    }
		}
	    }
	    Protocol {
		puts ","
		puts -nonewline "    \"protocol\": \"[string trim [
		    string map {802.11 ""} $val]]\""
	    }
	    ESSID {
		puts ","
		puts -nonewline "    \"ssid\": \"[string trim $val \"]\""
	    }
	    Channel {
		puts ","
		puts -nonewline "    \"channel\": \"[string trim $val]\""
	    }
	    Quality {
		puts ","
		#puts "$val $extra"
		set q [lindex [split $val /] 0]
		set s [lindex [split [lindex $extra 0] " "] 0]
		set n [lindex [split [lindex $extra 1] " "] 0]
		puts "    \"quality\": \"$q\","
		puts "    \"signal\": \"$s\","
		puts -nonewline "    \"noise\": \"$n\""
	    }
	    Encryption?key {
		puts ","
		puts -nonewline "    \"encryption\": \"[string trim $val]\""
	    }
	}
}

if {$cur} {
	if {![llength $authtypes]} {
		lappend authtypes "WEP"
	}
	puts ","
	puts "    \"auth\": \"$authtypes\""
	puts "  \}"
}

puts "\]"

