#!/usr/bin/python
#

# Copyright (C) 2013 Google Inc.
#
# This program 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.
#
# 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

import sys
import BaseHTTPServer
import SimpleHTTPServer


def main():
  if len(sys.argv) == 2:
    host = "127.0.0.1"

    (_, port) = sys.argv

  elif len(sys.argv) == 3:
    (_, port, host) = sys.argv

  else:
    sys.stderr.write("Usage: %s <port> [<host>]\n" % sys.argv[0])
    sys.stderr.write("\n")
    sys.stderr.write("Provides an HTTP server on the specified TCP port")
    sys.stderr.write(" exporting the current working directory. Binds to")
    sys.stderr.write(" localhost by default.\n")
    sys.exit(1)

  try:
    port = int(port)
  except (ValueError, TypeError), err:
    sys.stderr.write("Invalid port '%s': %s\n" % (port, err))
    sys.exit(1)

  handler = SimpleHTTPServer.SimpleHTTPRequestHandler

  server = BaseHTTPServer.HTTPServer((host, port), handler)
  server.serve_forever()


if __name__ == "__main__":
  main()
