#!/usr/bin/env python3
import os, sys, subprocess as sp

__version__ = '0.1.7'

PYBOARD_LOC = os.path.expanduser('~/.cache/picoedit/pyboard.py')
RESET_LEVEL = 'soft'

def interrupt(port):
	with open(port,'w') as f:
		f.write('\003')

def get(file, port, out_file=None):
	if not out_file:
		out_file = os.path.basename(file)
	print(f'Getting file: {file}...')
	interrupt(port)
	result = sp.run(
		[
			PYBOARD_LOC,
			'--no-soft-reset',
			'-d',port,
			'-f','cp',
			f':{file}',out_file
		]
	)
	if result.returncode != 0:
		print(f'Failed to get file: {file}')
	else:
		print(f'Wrote file to {out_file}')
	return result.returncode

def upload(file,port,out_file=None):
	if not out_file:
		out_file = os.path.basename(file)
	print(f'Uploading file: {file}...')
	interrupt(port)
	result = sp.run(
		[
			PYBOARD_LOC,
			'--no-soft-reset',
			'-d',port,
			'-f','cp',
			file,f':{out_file}'
		]
	)
	if result.returncode != 0:
		print(f'Failed to upload file: {file}')
	else:
		print(f'Uploaded file to {out_file}')
	return result.returncode

def soft_reset(port):
	with open(port, 'w') as f:
		f.write('\003\004')

def hard_reset(port):
	with open(port, 'w') as f:
		f.write('\003\001import machine\nmachine.reset()\004')

def reset(port):
	global RESET_LEVEL
	if RESET_LEVEL == 'soft':
		soft_reset(port)
	elif RESET_LEVEL == 'hard':
		hard_reset(port)

def bootloader(port):
	with open(port, 'w') as f:
		f.write('\003\001import machine\nmachine.bootloader()\004')

def main():
	global PYBOARD_LOC, RESET_LEVEL
	# Vars
	#VARS
	TEMP_DIR = '/tmp/picoedit'

	# Make sure we have pyboard.
	if not os.path.exists(PYBOARD_LOC):
		if not os.path.exists(pyb_dir := os.path.dirname(PYBOARD_LOC)):
			os.makedirs(pyb_dir)
		print('Pyboard not found.')
		print('Downloading pyboard...')
		sp.run(
			[
				'curl',
				'https://raw.githubusercontent.com/micropython/micropython/refs/heads/master/tools/pyboard.py',
				'-o',
				PYBOARD_LOC
			]
		)
		os.chmod(PYBOARD_LOC, 0o755)
		print('Done.')

	# Handle arguments
	#ARGS
	args = sys.argv[1:]

	port = None
	file = None
	operation = 'edit'
	out_file = None
	editor = 'editor'
	reset_after = False

	current = None
	for arg in args:
		if current:
			if current == 'port':
				port = arg
				current = None
			elif current == 'file':
				file = arg
				current = None
			elif current == 'editor':
				editor = arg
				current = None
			elif current == 'out':
				out_file = arg
				current = None
		else:
			if arg in ['-p', '--port']:
				current = 'port'
			elif arg in ['-f', '--file']:
				current = 'file'
			elif arg in ['-e', '--editor']:
				current = 'editor'
			elif arg in ['-g', '--get']:
				operation = 'get'
			elif arg in ['-u', '--upload']:
				operation = 'upload'
			elif arg in ['-o', '--out']:
				current = 'out'
			elif arg in ['-r', '--reset']:
				reset_after = True
				RESET_LEVEL = 'soft'
			elif arg in ['-h', '--hard-reset']:
				reset_after = True
				RESET_LEVEL = 'hard'
			elif arg in ['-b', '--bootloader']:
				operation = 'bootloader'
			else:
				if not port:
					port = arg
				elif not file:
					file = arg

	if not out_file:
		if file:
			out_file = os.path.basename(file)

	if reset_after and not file and port:
		reset(port)
		exit(0)

	#EDIT
	if operation == 'edit':
		if not port:
			print('Must specify port.')
			exit(1)
		if not file:
			print('Must specify file.')
			exit(1)
		#MKTEMP
		try:
			if not os.path.exists(TEMP_DIR):
				os.mkdir(TEMP_DIR) # Make temp dir
			if not os.path.isdir(TEMP_DIR): # If it somehow happens to be a file, just remove it.
				os.remove(TEMP_DIR)
				mkdir(TEMP_DIR)
		except Exception as e:
			print(f'Unable to create temp dir. "{e}"')

		#GETFILE
		local_file = (TEMP_DIR + '/' + os.path.basename(file)).replace('..', '').replace('//', '/') # Make sure there's no double / or .
		result = get(file,port,out_file=local_file)
		if result != 0:
			try:os.remove(local_file) # Make sure it's not half-written
			except Exception:pass # Just ignore
			exit(2)
		#EDIT
		os.system(f'"{editor}" "{local_file}"') # Open editor of choice
		#PUTFILE
		result = upload(local_file,port,out_file=file)
		if result != 0:
			result = os.system(f'cp "{local_file}" "{os.path.basename(file)}"')
			if result != 0:
				print('Failed to move file to current dir.')
				print(f'The file can be found at: {local_file}')
			else:
				print('Backed up file to current dir.')
				os.remove(local_file)
				print(f'Removed local file {local_file}')
			exit(2)
		#CLEAN
		os.remove(local_file)
		print(f'Removed local file {local_file}')
		if reset_after:
			reset(port)
	#GET
	elif operation == 'get':
		if not port:
			print('Must specify port.')
			exit(1)
		if not file:
			print('Must specify file.')
			exit(1)
		result = get(file,port,out_file)
		if result != 0:exit(2)
		exit(0)
	#UPLOAD
	elif operation == 'upload':
		if not port:
			print('Must specify port.')
			exit(1)
		if not file:
			print('Must specify file.')
			exit(1)
		result = upload(file,port,out_file)
		if reset_after:
			reset(port)
	elif operation == 'bootloader':
		if not port:
			print('Must specify port.')
		bootloader(port)

if __name__ == '__main__':
	main()
