package main

// import "os"
import "log"
import "time"
import "fmt"
import "os"
/*
import "reflect"
*/

import "git.wit.com/jcarr/shell"

func dhclient() {
	shell.Run("systemctl stop NetworkManager.service")
	shell.Run("systemctl disable NetworkManager.service")
	shell.Run("systemctl stop wpa_supplicant.service")
	shell.Run("killall wpa_supplicant")

	go shell.Daemon("wpa_supplicant -d -g /tmp/wpa-wlan0.sock -D wext -i wlan0 -c /etc/wpa_supplicant.conf", 1000 * time.Millisecond)

	log.Println("it for wpa_supplicant, then run dhclient")

	for {
		fmt.Println("running wpa_supplicant in the background")
		fmt.Println("need to figure out how to talk to it to see it's status")
		shell.Run("ifconfig wlan0")
		time.Sleep(10000 * time.Millisecond) // every 10 seconds
		filename := "/tmp/wit-install-done"
		if _, err := os.Stat(filename); !os.IsNotExist(err) {
			// log.Println("filename", filename, "does exist")
			return
		}
	}
}

func main() {
	parseConfig()

	go dhclient()

	shell.Run("sleep 20")
	shell.Run("dhclient wlan0")

	for {
		time.Sleep(10000 * time.Millisecond)
		ping := shell.Run("ping -c 1 git.wit.com")
		log.Println("ping returned ", ping)
		if (ping == 0) {
			break
		}
	}

	log.Println("MACHINE WIFI IS WORKING")
	log.Println("MACHINE WIFI IS WORKING")
	log.Println("MACHINE WIFI IS WORKING")
	log.Println("MACHINE WIFI IS WORKING")
	log.Println("MACHINE WIFI IS WORKING")

	shell.Run("sleep 360000") // force it to bomb after 1 hour so I can debug what to do
}
