# ugit
# micropython OTA update from github
# Created by TURFPTAx for the openmuscle project
# Check out https://openmuscle.org for more info
#
# Pulls files and folders from open github repository

import os
import urequests
import json
import hashlib
import binascii
import machine
import time
import network

global internal_tree

#### -------------User Variables----------------####
#### 
# Default Network to connect using wificonnect()
ssid = "HaoNet"
password = "nadesico"

# update url
update_url = 'https://fei-yen.jp/maya/toy-box/esp-web-flasher/ugit.py'
### -----------END OF USER VARIABLES ----------####

def pull(f_path,raw_url):
  print(f'pulling {f_path} from {raw_url}')
  #files = os.listdir()
  headers = {'User-Agent': 'ugit-turfptax'} 
  # ^^^ Github Requires user-agent header otherwise 403
  r = urequests.get(raw_url, headers=headers)
  try:
    new_file = open(f_path, 'w')
    bytes = new_file.write(r.content.decode('utf-8'))
    new_file.close()
    print(f'{bytes} bytes written')
  except:
    print('decode fail try adding non-code files to .gitignore')
    try:
      new_file.close()
    except:
      print('tried to close new_file to save memory durring raw file decode')

def wificonnect(ssid=ssid,password=password):
    print('Use: like ugit.wificonnect(SSID,Password)')
    print('otherwise uses ssid,password in top of ugit.py code')
    wlan = network.WLAN(network.STA_IF)
    wlan.active(False)
    wlan.active(True)
    wlan.connect(ssid,password)
    while not wlan.isconnected():
        pass
    print('Wifi Connected!!')
    print(f'SSID: {ssid}')
    print('Local Ip Address, Subnet Mask, Default Gateway, Listening on...')
    print(wlan.ifconfig())
    return wlan

def update():
    print('updates ugit.py to newest version')
    raw_url = update_url
    pull('ugit.py',raw_url)
