#!/usr/bin/env python

import sys, os, os.path
from acme_util import expect, warning, verbose_print, run_cmd

cwd = os.getcwd()

if __name__ == '__main__':
    if len(sys.argv) != 5:
        print('usage: migrate_dir_to_cime ACME_ROOT acme_subdir CIME_ROOT cime_subdir')
        exit(0)

    acme_root = os.path.abspath(sys.argv[1])
    acme_subdir = sys.argv[2]
    cime_root = os.path.abspath(sys.argv[3])
    cime_subdir = sys.argv[4]

    # Check dirs.
    if not os.path.exists(acme_root):
        print('Invalid ACME root: %s'%acme_root)
        exit(1)
    if not os.path.exists(os.path.join(acme_root, acme_subdir)):
        print('Invalid ACME subdir: %s'%acme_subdir)
        exit(1)
    if not os.path.exists(cime_root):
        print('Invalid CIME root: %s'%cime_root)
        exit(1)

    # Do a subtree split of the ACME subdirectory.
    os.chdir(acme_root)
    run_cmd('git checkout master')
    acme_subdir_branch = 'acme/%s'%acme_subdir
    print('Creating ACME branch %s for subdirectory %s...'%(acme_subdir_branch, acme_subdir))
    run_cmd('git branch -D %s'%acme_subdir_branch, ok_to_fail=True)
    run_cmd('git subtree split --prefix=%s master -b %s'%(acme_subdir, acme_subdir_branch))

    # Set up a remote for this ACME branch for CIME.
    print('Setting up %s remote within CIME repo...'%acme_subdir_branch)
    os.chdir(cime_root)
    run_cmd('git checkout master')
    run_cmd('git remote remove %s'%acme_subdir_branch, ok_to_fail=True)
    run_cmd('git remote add -t %s %s %s'%(acme_subdir_branch, acme_subdir_branch, acme_root))

    # Now fetch it.
    print('Fetching %s...'%acme_subdir_branch)
    run_cmd('git fetch %s'%acme_subdir_branch)

    os.chdir(cwd)

    # Now give our poor little user a hint of how to proceed.
    print('Now you can merge the ACME subdirectory into CIME using:')
    print('cd %s'%cime_root)
    print('git merge --squash -s recursive -Xsubtree=%s remotes/%s/%s'%(cime_subdir, acme_subdir_branch, acme_subdir_branch))
    print('And resolve conflicts with:')
    print('git mergetool')
