#!/usr/bin/env python2.7

# Copyright 2013 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.

import argparse
import os
import subprocess
import sys
from unittest import loader
from unittest import runner

for path in os.environ['PATH'].split(':'):
  if 'dev_appserver.py' in os.listdir(path):
    break
else:
  raise RuntimeError("Couldn't find dev_appserver.py")

# find and append appengine dir to path
app_engine_path = os.path.realpath(os.path.join(path,'dev_appserver.py'))
app_engine_path = os.path.dirname(app_engine_path)
sys.path.append(app_engine_path)

# add app.yaml path
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.join(current, '..')
sys.path.append(parent)

import appcfg
sys.path.extend(appcfg.EXTRA_PATHS)


"""
Some Ideas for what this util could be useful for besides testing

./tailbone/util validator resource_name relative_path_to/validator.py

# set the schema for a resource
./tailbone/util schema resource_name relative_path_to/schema.json

# get the schema for a resource
./tailbone/util schema resource_name

# backup the data
./tailbone/util backup

# backup the data for a resource
./tailbone/util backup resource_name

# load backup data to the test server
./tailbone/util restore backup.db

# clean and clear a database
./tailbone/util clear_database

# clean and clear memcache
./tailbone/util clear_memcache

# set the version name in the app.yaml
./tailbone/util version version_name

# update the server
./tailbone/util deploy

# run the local server
./tailbone/util run

# toggle using git versioning and branch name for the app.yaml version
./tailbone/util toggle_git

# generate the documentation branch for tailbone
./tailbone/util generate_docs
"""

def test(args):
  tests = loader.TestLoader().discover('tailbone')
  result = runner.TextTestRunner().run(tests)
  sys.exit(result.wasSuccessful())


parser = argparse.ArgumentParser(description="Tailbone helper utility.")
subparsers = parser.add_subparsers()

"""
Test tailbone
  This will also test any of your custom handlers.
./tailbone test
"""
parser_test = subparsers.add_parser("test")
parser_test.set_defaults(func=test)


if __name__ == '__main__':
  args = parser.parse_args()
  args.func(args)
