#! /usr/bin/python

#
# This script uses the current build directory as a template to create
# a new build directory (specified as the command-line argument).
#
# Note that the script can be invoked from anywhere, but will use the
# directory where the script resides as the template.
#

import sys
import os
import glob
import shutil

if len(sys.argv) != 2:
    print "Usage: %s <directory to create>" % sys.argv[0]
    sys.exit(1)

execdir = os.getcwd() # where the command was invoked from
olddir = sys.path[0]  # where this script lives
newdir = sys.argv[1]

if os.path.exists(newdir):
    print "Error: target directory %s already exists." % newdir
    sys.exit(1)

# Chdir to source dir while we check source files/links
os.chdir(olddir)

files_to_link = ['m5', 'ext', 'm5-test', 'SConstruct', 'build_options']
realpaths = {}

for f in files_to_link:
    if not os.path.exists(f):
        print "Error: needed file %s does not exist." % f
    realpath = os.path.realpath(f)
    realpaths[f] = realpath

# Everything looks good; go for it.

# Go back to exec dir, since newdir is relative to there.
os.chdir(execdir)
# Note that makedirs() will create intermediate dirs like 'mkdir -p'.
os.makedirs(newdir)
os.chdir(newdir)

for f in files_to_link:
    realpath = realpaths[f]
    print "Linking %s as %s." % (realpath, f)
    os.symlink(realpath, f)
