#!/usr/bin/python2

# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""grumprun compiles and runs a snippet of Python using Grumpy.

Usage: $ grumprun -m <module>             # Run the named module.
       $ echo 'print "hola!"' | grumprun  # Execute Python code from stdin.
"""

import argparse
import os
import string
import subprocess
import sys
import tempfile


parser = argparse.ArgumentParser()
parser.add_argument('-m', '--module', help='Run the named module')

module_tmpl = string.Template("""\
package main
import (
\t"os"
\t"grumpy"
\t"grumpy/lib/$package"
)
func main() {
\tos.Exit(grumpy.RunMain($alias.Code))
}
""")


def main(args):
  try:
    fd, path = tempfile.mkstemp(suffix='.go')
    if args.module:
      with os.fdopen(fd, 'w') as f:
        package = args.module.replace('.', '/')
        alias = package.split('/')[-1]
        f.write(module_tmpl.substitute(package=package, alias=alias))
    else:
      try:
        p = subprocess.Popen('grumpc /dev/stdin', stdout=fd, shell=True)
        if p.wait():
          return 1
      finally:
        os.close(fd)
    return subprocess.Popen('go run ' + path, shell=True).wait()
  finally:
    os.remove(path)


if __name__ == '__main__':
  sys.exit(main(parser.parse_args()))
