# OCCAM - Digital Computational Archive and Curation Service
# Copyright (C) 2014-2016 wilkie
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# This is the init process for x86-64 linux environments running in Docker.

import sys
import json
import subprocess
import os
import select

# Determine the ld.so.cache

if os.path.exists("/home/occam/task/ld.so.cache"):
  if os.path.exists("/etc/ld.so.cache"):
    os.remove("/etc/ld.so.cache")

  os.symlink("/home/occam/task/ld.so.cache", "/etc/ld.so.cache")
else:
  # Create ld.so.cache
  if os.path.exists("/sbin/ldconfig") or os.path.exists("/usr/bin/ldconfig") or os.path.exists("/bin/ldconfig"):
    if os.path.exists("/etc/ld.so.cache"):
      os.remove("/etc/ld.so.cache")

    with open("/home/occam/task/ld.so.cache", "a"):
      pass

    os.symlink("/home/occam/task/ld.so.cache", "/etc/ld.so.cache")
    for ldconfig_path in ["/sbin/ldconfig", "/usr/bin/ldconfig", "/bin/ldconfig"]:
      if os.path.exists(ldconfig_path):
        with open(os.devnull, 'w') as devnull:
          p = subprocess.Popen([ldconfig_path, "-v"], env = {"LD_LIBRARY_PATH": "/usr/lib:/usr/lib64:/usr/lib32:/lib32:/lib:/lib64"}, cwd = "/", stdout = devnull, stderr = devnull)
          p.communicate()

# Establish the user
if os.path.exists("/sbin/useradd") or os.path.exists("/usr/bin/useradd") or os.path.exists("/bin/useradd") or os.path.exists("/usr/sbin/useradd"):
  gid = os.getgid()
  uid = os.getuid()
  for groupadd_path in ["/sbin/groupadd", "/usr/bin/groupadd", "/bin/groupadd", "/usr/sbin/groupadd"]:
    if os.path.exists(groupadd_path):
      with open(os.devnull, 'w') as devnull:
        p = subprocess.Popen([groupadd_path, "occam", "--gid", str(gid)], cwd = "/", env = {"LD_LIBRARY_PATH": "/usr/lib:/usr/lib64:/usr/lib32:/lib32:/lib:/lib64"}, stdout = devnull, stderr = devnull)
        p.communicate()
  for useradd_path in ["/sbin/useradd", "/usr/bin/useradd", "/bin/useradd", "/usr/sbin/useradd"]:
    if os.path.exists(useradd_path):
      with open(os.devnull, 'w') as devnull:
        p = subprocess.Popen([useradd_path, "occam", "--uid", str(uid), "--gid", str(gid)], cwd = "/", env = {"LD_LIBRARY_PATH": "/usr/lib:/usr/lib64:/usr/lib32:/lib32:/lib:/lib64"}, stdout = devnull, stderr = devnull)
        p.communicate()

# Load object.json (the task manifest)

f = open("/home/occam/task/objects/0/task.json")
task = json.load(f)
f.close()

interactive = task.get('interactive', False)

processes = []

i = 0
for process in task.get('running', []):
  # For each process, determine the environment and run the object
  for obj in process.get('process', []):
    i = i + 1
    if 'init' in obj:
      # Read run command if there is one
      pass

    if 'run' in obj and i == len(process.get('process', [])):
      # Read the environment variables and run the command
      env = obj['run'].get('env', {})
      command = obj['run'].get('command')

      # Link mounted items
      for link in obj['run'].get('link', []):
        dest = link.get('name')
        src = link.get('target')

        if not (src is None or dest is None):
          # Create intermediate paths
          try:
            os.makedirs(os.path.dirname(dest))
          except:
            pass

          # Create the symlink
          if not os.path.exists(dest):
            os.symlink(src, dest)

      if not command is None:
        if not isinstance(command, list):
          command = [command]

        if not command[0].strip().startswith("/"):
          # Make it refer to the volume of the object if a relative path
          command[0] = os.path.join(obj.get('paths', {}).get('mount'), command[0].strip())

        env["OCCAM_INDEX"] = str(obj.get('index'))

        if not "PATH" in env:
          env["PATH"] = "/usr/bin"
        else:
          env["PATH"] = "%s:/usr/bin" % env["PATH"]

        # this is the main running process, wait for it
        cwd = (obj.get('paths', {}).get('cwd'))

        try:
          if interactive:
            #print("docker/x86-64: starting interactive process")
            import pty
            import tty
            import termios

            # save original tty setting then set it to raw mode
            old_tty = termios.tcgetattr(sys.stdin)
            tty.setraw(sys.stdin.fileno())

            # open pseudo-terminal to interact with subprocess
            host, guest = pty.openpty()

            p = subprocess.Popen(command, preexec_fn=os.setsid, env = env, cwd = cwd, stdin=guest, stdout=guest, stderr=guest, universal_newlines=True)

            os.close(guest)

            while p.poll() is None:
              r, w, e = select.select([sys.stdin, host], [], [])
              if sys.stdin in r:
                d = os.read(sys.stdin.fileno(), 10240)
                os.write(host, d)
              elif host in r:
                o = None
                try:
                  o = os.read(host, 10240)
                except OSError as e:
                  pass
                if o:
                  os.write(sys.stdout.fileno(), o)

            # restore tty settings back
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
          else:
            stdoutBuffer = ""
            stderrBuffer = ""

            stdin = None
            stdinPath = os.path.join(obj.get('paths', {}).get('localMount'), "stdin")
            if os.path.exists(stdinPath):
              stdin = open(stdinPath, "rb")

            with open(os.path.join(obj.get('paths', {}).get('localMount'), "stdout"), "w+") as sout:
              with open(os.path.join(obj.get('paths', {}).get('localMount'), "stderr"), "w+") as serr:
                p = subprocess.Popen(command, env = env, cwd = cwd, stdin = stdin, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
                stdout = p.stdout
                stderr = p.stderr

                readers = [stdout, stderr]
                closed = []

                while True:
                  readable, writable, exceptional = select.select(readers, [], readers)

                  numRead = 0

                  for reader in readable:
                    read = reader.read(1)
                    numRead = len(read)

                    if reader is stdout:
                      sout.write(read)
                      stdoutBuffer = stdoutBuffer + read
                      if read == "\n":
                        sys.stdout.write(stdoutBuffer)
                        sys.stdout.flush()
                        stdoutBuffer = ""
                    if reader is stderr:
                      serr.write(read)
                      sout.write(read)
                      stderrBuffer = stderrBuffer + read
                      if read == "\n":
                        sys.stderr.write(stderrBuffer)
                        sys.stderr.flush()
                        stderrBuffer = ""

                    if len(read) == 0:
                      closed.append(reader)
                      readers.remove(reader)

                  if len(readable) == 0 and process.poll() is not None:
                    break

                  if numRead == 0 and len(closed) == 2:
                    break

            p.communicate()
        except OSError as e:
          if e.errno == 2:
            print >> sys.stderr, "Error %s: No such file or directory: %s" % (str(e.errno), " ".join(command))
          else:
            print >> sys.stderr, "OS Error %s" % (e.errno)
