#!/usr/bin/env python
# encoding: utf-8
#build on top of https://npyscreen.readthedocs.io/introduction.html
# ulbricht@innoroute.de 2021
import npyscreen
import wget
from configobj import ConfigObj
import os
import sys
from rt_hat import FPGA as RT_HAT_FPGA

selected=""
modes={"TSN endpoint (default)":"_uc0"}
def is_root():
    return os.geteuid() == 0
				
class TestApp(npyscreen.NPSApp):
    def main(self):
        global selected
        F  = npyscreen.Form(name = "Realtime-HAT Bitstream selection and update",)
        ms = F.add(npyscreen.TitleSelectOne, max_height=4, value = [0,], name="Select the bitstream to download.",
                values = list(modes.keys()), scroll_exit=True)


        F.edit()

        selected=ms.get_selected_objects()
        print("möp")

def load_bs(bs_name):
    print("Downloading config file...")
    try:
    	if os.path.exists("/usr/share/InnoRoute/bs_info.conf"):
    		os.remove("/usr/share/InnoRoute/bs_info.conf")
    	configfile=wget.download("https://raw.githubusercontent.com/InnoRoute/RT-HAT-FPGA/main/HAT/"+bs_name+".conf",out="/usr/share/InnoRoute/bs_info.conf") 
    	bsname=str([line for line in open(configfile) if "BS_file" in line][0].split('"')[1])
    	print("\nDownloading bitstream...")
    	if os.path.exists("/usr/share/InnoRoute/user_bitstream.bit"):
    		os.remove("/usr/share/InnoRoute/user_bitstream.bit")
    	bsfile=wget.download(bsname,out="/usr/share/InnoRoute/user_bitstream.bit") 
    	print("\nload bitstream")
    	os.system('cat /usr/share/InnoRoute/bs_info.conf | grep -E "C_ADDR_|FEATURE_" >/usr/share/InnoRoute/hat_env.sh')
    	os.system('/usr/share/InnoRoute/INR_write_bitstream /usr/share/InnoRoute/user_bitstream.bit')	
    except Exception as e:
    	print("Download failed, check your internet connection!\n"+str(e))

if __name__ == "__main__":
    if is_root()==False:
    	print("need to run with sudo")
    	exit(1)		
    App = TestApp()
    if len(sys.argv)==1:
    	App.run()
    	selected=modes[selected[0]]
    else:
    	selected=sys.argv[1]
    load_bs(selected)
    RT_HAT_FPGA.init("/usr/share/InnoRoute/hat_env.sh")
    license=int(RT_HAT_FPGA.status()['LICENSE'],16)
    print("License:"+hex(license))
    if (license==0 and selected !="_uc0"):
    	print("##################################")
    	print("This feature is not available for your Device. Please contact info@innoroute.de to extend your license.")
    	print("##################################")
    	print("loading default bitstream...")
    	load_bs("uc0")
    print("done")


