#!/usr/bin/env python3

from os import path, listdir
from sys import argv
import datetime
from subprocess import run, PIPE, DEVNULL
import tempfile
from shutil import copyfile



def h_topdir():
	rc = 0
	while rc == 0:
		rc = run(['hcd','::'], stderr=DEVNULL).returncode




my_name, *cmds = argv

srcimage = 'SourceForEmulator.dmg'

cmdline = ' '.join(cmds)

scriptfolder = path.dirname(path.abspath(__file__))

vmac_app = path.join(scriptfolder, 'Mini vMac 9590.app') # requested for later: -t mc64 -m II -sound 0 -speed a -bg 1 -as 0
vmac_exec = path.join(vmac_app, 'Contents', 'MacOS')
vmac_exec = path.join(vmac_exec, next(l for l in listdir(vmac_exec) if not l.startswith('.')))

bootimg = path.join(scriptfolder, 'MPW-VM.dmg')
backupimg = path.join(scriptfolder, 'MPW-VM-KnownGood.dmg')

hsync = path.join(scriptfolder, 'hsync')
hsyncback = path.join(scriptfolder, 'hsyncback')

if not path.exists(bootimg):
	print('Creating new scratch boot disk.')
	copyfile(backupimg, bootimg)




if cmds:
	mpw_cmd = """# This is an auto-generated MPW script!
Echo '# %s'
Echo '# %s'
SetDirectory Src:
Begin
	%s
End > "{Boot}StdOut"
Echo
Move -y "{__Startup__i}" "{Boot}Trash:"
ShutDown -y
""" % (datetime.datetime.now(), cmdline, cmdline)
else:
	mpw_cmd = """# This is an auto-generated MPW script!
SetDirectory Src:
Move -y "{__Startup__i}" "{Boot}Trash:"
"""

mpw_cmd = mpw_cmd.replace('\n','\r')

with open('/tmp/AutoGen', 'w') as f:
	f.write(mpw_cmd)
	tmp_path = f.name


run([hsync], check=True)



run(['SetFile', '-t', 'TEXT', '-c', 'MPS ', tmp_path], check=True)
run(['macbinary', 'encode', '--overwrite', '-o', tmp_path+'.bin', tmp_path], check=True)

run(['hmount', bootimg], check=True, stdout=DEVNULL)
h_topdir()
run(['hcopy', '-m', tmp_path+'.bin', ':MPW:Startup Items:'], check=True)
run(['humount'], check=True)




# http://www.gryphel.com/c/minivmac/osx_note.html
# Disable Path Randomization
run(['xattr', '-cr', vmac_app], check=True)

run([vmac_exec, bootimg, srcimage], check=True)



run([hsyncback], check=True)




if cmds:
	run(['hmount', bootimg], check=True, stdout=DEVNULL)
	run(['hcopy', '-t', ':StdOut', '/tmp/StdOut'], check=True)
	run(['humount'], check=True)

	with open('/tmp/StdOut') as f:
		print(f.read(), end='')
