# Setup file to get the core   #
# functionality of my microIDE #
# on an MicroPython ESP32 chip # 
#                              #
# dependant on:                #
#   _thread                    #
#   socket / usocket           #
#   os / uos                   #
#                              #
#  [WILL NOT WORK ON ESP8266]  #
#   

#HARD RESET FOR CORUPTED FILES #
# import os
# import flashbdev
# os.VfsFat.mkfs(flashbdev.bdev)

import socket
import network

#Ensure wifi is connect
wlan0 = network.WLAN(network.STA_IF)
while not wlan0.isconnected():
  print("No Network")

#Connect to http
addr = socket.getaddrinfo('git.microide.com', 80)[0][-1]
s = socket.socket()
s.connect(addr)
s.send(bytes('GET /microIDE.py HTTP/1.0\r\nHost: git.microide.com\r\n\r\n', 'utf8'))
data=s.readline()

#Ensure File is found
while not '200 OK' in data: #Locks up the function - on purpose
  data=s.readline()
while data != b'\r\n':
  data=s.readline()
  
#Write File to microIDE.py
f=open('microIDE.py','w')
while True:
  data = s.recv(4096)
  if data:
    f.write(data)
  else:
    break
f.close()
s.close()

#initial run of mciroIDE
import microIDE