package main

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

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

func main() {
	parseConfig()

	if _, err := os.Stat("/home/factory"); os.IsNotExist(err) {
		shell.Run("mkdir /home/factory")
	}

	if _, err := os.Stat("/usr/bin/dialog"); os.IsNotExist(err) {
		shell.Run("apt install dialog")
	}

	if _, err := os.Stat("/dev/mmcblk0p2"); !os.IsNotExist(err) {
		log.Println("device /dev/mmcblk0p2 exists")
	} else {
		log.Println("device /dev/mmcblk0p2 does not exist")
		fail()
	}

	shell.Run("mount /dev/mmcblk0p2 /home/factory")

	imagename := "factory-2019-01-20"
	fullname :=  "/home/factory/" + imagename

	// if the image does not exist, try to wget it
	if _, err := os.Stat(fullname); os.IsNotExist(err) {
		log.Println("filename", fullname, "does not exist")
		shell.Run("cd /home/factory")
		shell.Run("wget -c " + "http://fire.lab.wit.com/factory/" + imagename)
	}

	if _, err := os.Stat(fullname); !os.IsNotExist(err) {
		log.Println("filename", fullname, "exists. dd here")
		shell.Run("dd if=" + fullname + " of=/dev/mmcblk2 bs=1M status=progress oflag=sync")
		succeeded()
	} else {
		log.Println("filename", fullname, "does not exist")
		fail()
	}

}

func fail () {
	log.Println("")
	log.Println("")
	log.Println("")
	log.Println("INSTALL FAILED")
	log.Println("INSTALL FAILED")
	log.Println("INSTALL FAILED")
	log.Println("INSTALL FAILED")
	log.Println("INSTALL FAILED")
	log.Println("INSTALL FAILED")
	log.Println("")
	log.Println("")
	log.Println("")

	os.Exit(-1)
}

func succeeded () {
	log.Println("")
	log.Println("")
	log.Println("")
	log.Println("INSTALL SUCCEEDED")
	log.Println("INSTALL SUCCEEDED")
	log.Println("INSTALL SUCCEEDED")
	log.Println("INSTALL SUCCEEDED")
	log.Println("INSTALL SUCCEEDED")
	log.Println("INSTALL SUCCEEDED")
	log.Println("")
	log.Println("")
	log.Println("")

	shell.Run("dialog --ascii-lines --msgbox 'Flash_Image_Completed' 10 70")
	shell.Run("poweroff")

	os.Exit(0)
}
