from pathlib import Path
import shutil,re,subprocess,json
base=Path('/home/davit/Git2/mindblown-classics')
for slug,archive,project in [('passage','Passage_v4_UnixSource','gamma256'),('gravitation','Gravitation_v3_UnixSource','game5')]:
 r=base/slug;src=r/'upstream'/archive;work=r/'source'
 if not work.exists():shutil.copytree(src,work)
 game=work/project/'gameSource';p=game/'game.cpp';s=(src/project/'gameSource/game.cpp').read_text()
 s='#include <emscripten.h>\n'+s
 s=s.replace('SDL_GetKeyState', 'SDL_GetKeyboardState')
 s=s.replace('#include <SDL/SDL.h>', '#include <SDL/SDL.h>\nextern \"C\" EMSCRIPTEN_KEEPALIVE void webMute(int muted) { SDL_PauseAudio(muted); }')
 s=s.replace('while( SDL_WaitEvent( &event ) ) {','emscripten_sleep(16);\n        while( SDL_PollEvent( &event ) ) {')
 s=s.replace('Thread::staticSleep( (int)( extraTime * 1000 ) );','emscripten_sleep( (int)( extraTime * 1000 ) );')
 s=s.replace('while( !done ) {','while( !done ) {\n        emscripten_sleep(1);\n        while( EM_ASM_INT({ return document.hidden; }) ) emscripten_sleep(100);\n        EM_ASM({ window.gameX=$0;window.gameY=$1;window.gameScore=$2; }, playerX,playerY,score);')
 s=s.replace('char hit = waitForKeyOrButton();','EM_ASM({ window.gameReady?.(); });\n    char hit = waitForKeyOrButton();\n    if(hit) EM_ASM({ window.gameStarted?.(); });')
 s=s.replace('    unsigned long netTime =', '    EM_ASM({ window.gameEnded?.($0,$1); }, score,!quit);\n    unsigned long netTime =')
 p.write_text(s)
 (game/'settings/fullscreen.ini').write_text('0')
 (game/'settings/screenWidth.ini').write_text('600' if slug=='passage' else '396')
 (game/'settings/screenHeight.ini').write_text('480' if slug=='passage' else '400')
 out=r/'dist';out.mkdir(exist_ok=True)
 mg=work/'minorGems'
 sources=['io/file/linux/PathLinux.cpp','util/stringUtils.cpp','util/StringBufferOutputStream.cpp','util/SettingsManager.cpp','system/unix/TimeUnix.cpp','system/linux/ThreadLinux.cpp']
 if slug=='passage':sources+=['crypto/hashes/sha1.cpp','formats/encodingUtils.cpp']
 gameSources=['game','blowUp','World','map','common','score','musicPlayer','Timbre','Envelope']+(['landscape'] if slug=='passage' else ['particles','Gradient'])
 args=['/home/davit/Git2/mohaa-web/emsdk/upstream/emscripten/em++','-O2','-std=c++11','-Wno-deprecated','-Wno-writable-strings','-I'+str(work),'-sUSE_SDL=1','-sASYNCIFY=1','-sALLOW_MEMORY_GROWTH=1','-sFORCE_FILESYSTEM=1','-sEXPORTED_RUNTIME_METHODS=["FS","ccall"]','-sEXIT_RUNTIME=0','-o',str(out/'game.js')]+[str(mg/s) for s in sources]+[str(game/(s+'.cpp')) for s in gameSources]+['--preload-file','graphics','--preload-file','music','--preload-file','settings']
 (r/'build-command.json').write_text(json.dumps(args,indent=2))
 with (r/'build.log').open('w') as log:res=subprocess.run(args,cwd=game,stdout=log,stderr=subprocess.STDOUT)
 print(slug,res.returncode,flush=True)
