#!/usr/bin/env python
"""
Run msys command from cygwin.

Usage:
  msys.py <msys command>

Examples:
  msys.py python -i

Installation:
  Copy this script to cygwin's /usr/local/bin directory
  and fix paths specific to your local installation (see
  `### Fix ..' comments below).

Author: Pearu Peterson <pearu@cens.ioc.ee>
Created: Feb 2, 2004
"""

__revision__ = '$Id: msys.py,v 1.3 2004/04/11 23:32:28 pearu Exp $'

import os
import sys

DEBUG = 0

### Fix drive, directory paths, msys version, Python path:
cygwin_prefix = '/c/cygwin'
msys_prefix = '/cygdrive/c/msys/1.0'
win32_python_path = '/cygdrive/c/Python23'
###

if len(sys.argv)==2 and sys.argv[1]=='--help':
    print 'Usage: msys.py <msys command>'
    sys.exit()

# Utility functions:

def msyspath(path):
    path = os.path.abspath(path)
    if path.startswith('/cygdrive/'):
        l = path.split(os.sep)
        return os.sep.join([l[2]+':']+l[3:])
    return cygwin_prefix + path

def cygwin_paths_last(paths):
    new_paths = []
    win_paths = []
    cyg_paths = []
    for path in paths:
        if path.startswith('/cygdrive/'):
            if path not in new_paths:
                new_paths.append(path)
        elif path not in cyg_paths:
            cyg_paths.append(path)
    return cyg_paths + new_paths


# Compose MSYS command:

cwd = msyspath(os.getcwd())
if DEBUG:
    print "CWD:",cwd
    print "sys.argv[1:]:",sys.argv[1:]
c = 'cd %s' % (cwd) + ' && '
for s in sys.argv[1:]:
    if ' ' in s:
        c = c + ' \\"%s\\"' % (s)
    else:
        c = c + ' %s' % (s)
c = msys_prefix + '/bin/sh.exe --login -c "%s"' % c

# Map environment to MSYS compatible:

old_env = {}

for var in ['PATH','PYTHONPATH','MANPATH']:
    if not os.environ.has_key(var):
        continue
    old_value = os.environ[var]
    if var == 'PATH':
        new_value = os.pathsep.join([win32_python_path] +\
                      cygwin_paths_last(old_value.split(os.pathsep)))
    else:
        new_value = os.pathsep.join(cygwin_paths_last(old_value.split(os.pathsep)))
    old_env[var] = old_value
    os.environ[var] = new_value

for var in ['ATLAS','BLAS','BLAS_SRC','LAPACK','LAPACK_SRC','FFTW',
            'DJBFFT']:
    if not os.environ.has_key(var):
        continue
    old_value = os.environ[var]
    new_value = msyspath(old_value)
    if new_value != old_value:
        old_env[var] = old_value
        os.environ[var] = new_value

# Run command:

if DEBUG:
    print "Command:",c
s = os.system(c)
if DEBUG:
    print "Status:",s

# Restore cygwin environment:

for key,value in old_env.items():
    os.environ[key] = value

# Exit with command status:

sys.exit(s)

#EOF
