#!/usr/bin/env python
#
import os, re, sys

sys.argv.pop(0)                         # remove script name
try:
    eupspython = sys.argv.pop(0)
    eupsdir = sys.argv.pop(0)
    prefix = sys.argv.pop(0)
except IndexError:
    print("Usage: mksetup EUPS_PYTHON EUPS_DIR EUPS_PATH [SETUP_ALIASES]", file=sys.stderr)

    sys.exit(1)

try:
    vals = sys.argv.pop(0).split(":")
    setup_aliases = {"setup" : vals[0], "unsetup" : vals[1]}
except IndexError:
    setup_aliases = {}

ups_db = os.path.join(prefix, "ups_db")

bindir = os.path.join("$EUPS_DIR","bin")
pythondir = os.path.join("$EUPS_DIR","python")
setup = os.path.join('$EUPS_DIR',"bin","eups_setup");

# Keep only one copy of each directory in sys.argv[1], but make sure that sys.argv[2] is present
unique_path="""
import sys
pp = []
for d in sys.argv[1].split(":"):
    if d and d not in pp:
        pp += [d]
if not sys.argv[2] in pp:
    pp = [sys.argv[2]] + pp
print(":".join(pp))"""

print("Writing a csh startup script");
try:
    fd = open("setups.csh", "w")
except IOError as e:
    print("Unable to open setups.csh: %s" % e, file=sys.stderr)
    sys.exit(1)
#
# Problems with multi-line scripts in csh required us to use a
# here document, and pre-substitute the path rather than pass
# it in from the command line
#
unique_eups_path = unique_path
unique_eups_path = re.sub(r"sys\.argv\[1\]", "\"$EUPS_PATH\"", unique_eups_path)
unique_eups_path = re.sub(r"sys\.argv\[2\]", "\"%s\"" % prefix, unique_eups_path)

print("""\
###
### AUTOGENERATED BY EUPS' configure script (via bin/mksetup)
###

setenv EUPS_SHELL csh

if ("$?EUPS_DIR" == "1" ) then
   setenv PATH `echo $PATH | perl -pe "s|:%(bindir)s||g"`
   if ("$?PYTHONPATH" == "1" ) then
      setenv PYTHONPATH `echo $PYTHONPATH | perl -pe "s|:%(pythondir)s||g"`
   endif
   setenv EUPS_DIR "${EUPS_DIR}"
else
   setenv EUPS_DIR "%(eupsdir)s"
endif
set eupslocalpath = `echo "$EUPS_DIR" | sed -e "s/ /-+-/g"`

if ("$?EUPS_PATH" == "0" ) then
    setenv EUPS_PATH ""
endif

# Set EUPS_PATH, appending any pre-existing EUPS_PATH (and only keeping
# one copy of each directory)
setenv EUPS_PATH `python -E` << EOT
%(unique_eups_path)s
EOT
set _eups_path = "$EUPS_PATH"

# csh shells die if variables are undefined, so we'll define an (empty) DYLD_LIBRARY_PATH
# if there isn't one already
if (! $?DYLD_LIBRARY_PATH) then
    setenv DYLD_LIBRARY_PATH ""
endif

# setup EUPS, using EUPS
# n.b.: we reset the flavor in SETUP_EUPS so eups doesn't show up in 'eups list'
#       and similar. This is for backwards compatibility.
eval `"%(setup)s" "DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}" eups -r "$EUPS_DIR"`
setenv SETUP_EUPS "eups LOCAL:$eupslocalpath -f (none) -Z (none)"
setenv EUPS_PATH "$_eups_path"            # make sure that the setup script didn't reset EUPS_PATH
unset eupslocalpath _eups_path

""" % {"bindir" : bindir, "eupsdir" : eupsdir, "prefix" : prefix, \
           "pythondir" : pythondir, "setup" : setup,  "unique_eups_path" : unique_eups_path, \
           "eupspython" : eupspython }, file=fd)

for s in setup_aliases.keys():
    print("alias %s %s" % (setup_aliases[s], s), file=fd)

del fd

print("Writing a sh startup script");
try:
    fd = open("setups.sh", "w")
except IOError as e:
    print("Unable to open setups.sh: %s" % e, file=sys.stderr)
    sys.exit(1)

print("""\
###
### AUTOGENERATED BY EUPS' configure script (via bin/mksetup)
###

# this is how EUPS knows which shell it's operating under
export EUPS_SHELL=sh

# allow the user to override EUPS_DIR
export EUPS_DIR=${EUPS_DIR:-%(eupsdir)s}
eupslocalpath=$(echo "$EUPS_DIR" | sed -e "s/ /-+-/g")

# Set EUPS_PATH, appending any pre-existing EUPS_PATH (and only keeping
# one copy of each directory)
export EUPS_PATH=`"%(eupspython)s" -E -c '%(unique_path)s' "$EUPS_PATH" "%(prefix)s"`
_eups_path=$EUPS_PATH

# setup EUPS, using EUPS
# n.b.: we reset the flavor in SETUP_EUPS so eups doesn't show up in 'eups list'
#       and similar. This is for backwards compatibility.
eval `"%(setup)s" "DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}" eups -r "$EUPS_DIR"`
export SETUP_EUPS="eups LOCAL:$eupslocalpath -f (none) -Z (none)"
export EUPS_PATH=$_eups_path            # make sure that the setup script didn't reset EUPS_PATH
unset eupslocalpath _eups_path

# bash auto-completion
if [ X$BASH_COMPLETION != X -a -f "$EUPS_DIR/etc/bash_completion.d/eups" ]; then
    source "$EUPS_DIR/etc/bash_completion.d/eups"
fi
""" \
    % {"bindir" : bindir, "eupsdir" : eupsdir, "prefix" : prefix, \
           "pythondir" : pythondir, "setup" : setup, "unique_path" : unique_path, \
           "eupspython" : eupspython }, file=fd)

for s in setup_aliases.keys():
    print("alias %s=%s" % (setup_aliases[s], s), file=fd)

del fd
#
# Keep setups.zsh purely for backwards compatibility
#
print("Linking zsh/dash startup script from sh one for historical reasons");
setups_zsh = "setups.zsh"
if os.path.exists(setups_zsh):
    os.unlink(setups_zsh)
os.symlink("setups.sh", setups_zsh)

sys.exit(0)
