#!/usr/bin/env python
#
# Copyright 2010 Mike Wakerly <opensource@hoho.com>
#
# This file is part of the Pykeg package of the Kegbot project.
# For more information on Pykeg or Kegbot, see http://kegbot.org/
#
# Pykeg is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Pykeg 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pykeg.  If not, see <http://www.gnu.org/licenses/>.

import django

import os
import subprocess
import sys

from django.core import management
from pykeg.core.util import get_version
from pykeg.util import bugreport

if sys.version_info < (2, 7):
  sys.stderr.write('Error: Kegbot needs Python 2.7 or newer.\n\n'
      'Current version: %s\n' % sys.version)
  sys.exit(1)

if __name__ == "__main__":
  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pykeg.settings")

  # Override some special commands.
  if len(sys.argv) > 1:
    cmd = sys.argv[1]
    if cmd == 'version':
        # Hack: Django's `version` command cannot be overridden the usual way.
        print 'kegbot-server {}'.format(get_version())
        sys.exit(0)
    elif cmd == 'run_gunicorn':
        # run_gunicorn was deprecated upstream.
        cmd = 'gunicorn pykeg.web.wsgi:application {}'.format(' '.join(sys.argv[2:]))
        sys.stderr.write('Warning: run_gunicorn is deprecated, call `{}` instead.\n'.format(cmd))
        ret = subprocess.call(cmd, shell=True)
        sys.exit(ret)
    elif cmd == 'bugreport':
      ret = bugreport.take_bugreport()
      sys.exit(ret)

  django.setup()
  management.execute_from_command_line()
