#!/usr/bin/env python
from __future__ import print_function
import os,sys,subprocess

TRACE = os.environ.get('GUP_XTRACE','0') == '1'

def run(cmd):
	if TRACE:
		print(' + ' + ' '.join(cmd))
	try:
		subprocess.check_call(cmd)
	except (subprocess.CalledProcessError, KeyboardInterrupt) as e:
		sys.exit(1)

dest, target = sys.argv[1:]
def dune(*targets):
	return lambda: (
		run(['dune', 'build'] + list(targets))
	)

def gup(*targets):
	return lambda: (
		run(['gup', '-u'] + list(targets))
	)

mapping = {
	'client': dune('passe.install'),
	'native': gup('client', 'server'),
	'js': dune('@src/www/main.bc.js'),
	'www': dune('@src/www/all'),
	'passe.install': dune('passe.install'),
	# 'passe-server.install': dune('passe-server.install'),
	'res': gup('src/www/res/all'),
	'mirage-unix': gup('_build/mirage-unix'),
	'mirage-ukvm': gup('_build/mirage-ukvm'),
}

action = mapping[target]
subprocess.check_call(['gup','--always'])
action()
