#! /usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import subprocess
import sys
import time


sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import packaging


def main():
  root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  with packaging.TempAppDir(root_dir, symlinks=True) as temp_app_dir:
    yaml_files = list(file_name for file_name in packaging.Yamls(temp_app_dir)
                      if os.path.basename(file_name) != 'cron.yaml')
    args = ['dev_appserver.py'] + yaml_files + sys.argv[1:]

    server = subprocess.Popen(args, cwd=temp_app_dir)
    try:
      server.wait()
    except KeyboardInterrupt:
      server.wait()
      # It's pretty much impossible to wait for all the subprocesses of the dev
      # server to finish, as they all shut down asynchronously. But their
      # shutdown timeouts are generally 1 second, so that's probably enough.
      time.sleep(1)


if __name__ == '__main__':
  main()