#!/usr/bin/env python
# Haoyi 2022/09/08
import os,sys,re
import copy
import shutil
_version="1"
files = sys.argv[1:]
print("Input argument is %s" %(sys.argv[1:]))
currentPath = os.getcwd()
zygoteRoot = os.path.expanduser("~/.gurutools/flutter_zygote")
zygotePath = zygoteRoot + "/lib/zygote"
zygoteVersion = zygoteRoot + "/.version"

os.system('rm -fr %s' %(zygotePath + '/*'))
os.system('rm -fr %s' %(zygoteRoot + '/guru_spec.yaml'))

def syncZygote():
    os.chdir(zygoteRoot)
    os.system("git pull --rebase")
    os.system("flutter pub get")
    os.chdir(currentPath)

if (os.path.exists(zygoteRoot) != True):
    print("init zygote...")
    os.makedirs(zygoteRoot)
    os.chdir(zygoteRoot)
    os.system("git clone git@github.com:castbox/flutter_zygote.git ./")
    os.system("flutter pub get")
    os.chdir(currentPath)

if (os.path.exists(zygoteVersion) != True):
    syncZygote()
else:
    with open(zygoteVersion, "r") as f:
        version = f.read();
        if (_version > version):
            syncZygote()
        else:
            print("Current zygote.py is up to date")

# os.system('rm -fr %s' %(zygoteRoot + '/guru_spec.yaml'))
targetFiles = []
for f in files:
    if (os.path.isfile(f)):
        srcDir = os.path.dirname(f)
        srcName = os.path.basename(f)
        if (srcName == 'guru_spec.yaml'):
            shutil.copy(f, zygoteRoot + '/guru_spec.yaml')
            continue

        dstDir = zygotePath + srcDir
        dstFile = dstDir + '/' + srcName
        
        os.makedirs(dstDir, exist_ok=True)
        shutil.copy(f, dstFile)

        os.path.dirname(f)
        generatedName = srcName.replace('.', '.g.')
        targetFiles.append((dstDir + '/' + generatedName, srcDir + '/' + generatedName))

os.chdir(zygoteRoot)
os.system('flutter packages pub run build_runner build --delete-conflicting-outputs')
os.chdir(currentPath)
for f in targetFiles:
    print(f[0] + ' => ' + f[1])
    shutil.copy(f[0], f[1])
    
os.system('rm -fr %s' %(zygotePath + '/*'))
os.system('rm -fr %s' %(zygoteRoot + '/guru_spec.yaml'))
# os.system('cd -')