#!/usr/bin/env python

import os
import sys
args = sys.argv[1:]

if "SAGE_SRC" not in os.environ:
    raise RuntimeError("The environment variable SAGE_SRC must be set.")
SAGE_SRC = os.environ["SAGE_SRC"]

# args can have length 0, in case we're printing a usage message (see trac 12207)
pyx_file = os.path.abspath(args[-1]) if len(args) else None
include_sage_flags = False

if pyx_file and pyx_file.endswith('.spyx'):
    sys.stderr.write("WARNING: running sage --cython on .spyx files is deprecated, use the .pyx extension instead\n")
    spyx_file = pyx_file
    pyx_file = pyx_file[:-5] + '.pyx'
    args[-1] = pyx_file
    f = open(pyx_file, 'w')
    f.write("include 'sage/ext/stdsage.pxi'\ninclude 'sage/ext/cdefs.pxi'\ninclude 'cysignals/signals.pxi'\n\n")
    f.write(open(spyx_file).read())
    f.close()
    include_sage_flags = True

if pyx_file and pyx_file.startswith(SAGE_SRC):
    include_sage_flags = True

if '-sage' in args:
    include_sage_flags = True
    args.remove('-sage')
elif '-no-sage' in args:
    include_sage_flags = False
    args.remove('-no-sage')

if include_sage_flags:
    args = ['--embed-positions', '-I%s' % SAGE_SRC] + args

args.insert(0, 'sage-cython')
os.execlp('cython', *args)
