#!/usr/bin/env bash

set -eou pipefail

# 1. Create a configuration file for pypicloud from a few env vars
# 2. Run pypicloud

cat >server.ini <<EOF
[app:main]
use = egg:pypicloud

pyramid.reload_templates = False
pyramid.debug_authorization = False
pyramid.debug_notfound = False
pyramid.debug_routematch = False
pyramid.default_locale_name = en

pypi.fallback = cache
pypi.always_show_upstream = True

pypi.default_read = everyone
pypi.cache_update = everyone
pypi.default_write = authenticated

pypi.storage = s3
storage.bucket = ${PYPICLOUD_STORAGE_BUCKET}
storage.public_url = true
storage.server_side_encryption = AES256

pypi.db = dynamo
db.region_name = ${PYPICLOUD_DB_REGION}
db.namespace = ${PYPICLOUD_DB_NAMESPACE}

auth.admins =
  admin

user.admin = \$6\$rounds=656000\$PylsQLnOu/OIGND.\$bRJyR/Dns2Ev47McvsgLYaenFHsmXjQOAYah1N5q2qVpw6WrGZyaMVUEeM4K.8cmNgqNKST9KV/bJQEgCBONV1
user.zoox = \$6\$rounds=656000\$1mi9kedRvhXJYmeV\$vOcelu9POvm3uavObMDSn3zSt3F.GbrtCjuTl3VyupsU3trtuEuQ40QXrRZMIImKNplBRYLU5.g6ZP1xEVrX1/

# For beaker
session.encrypt_key = rVCkFl2I3liLxhpRnP7N7S/aAxSEo7jZAYsfXFfvUW4=
session.validate_key = HbXClA9mdSoZ/sDxbtxpYHvoVGHNWsgPZ/MjkrBwPVI=
session.secure = True

###
# wsgi server configuration
###

[server:main]
use = egg:waitress#main
host = 0.0.0.0
port = 6543
url_scheme = ${PYPICLOUD_DEFAULT_URL_SCHEME:-http}

###
# logging configuration
# http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/logging.html
###

[loggers]
keys = root, boto, pypicloud

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = INFO
handlers = console

[logger_waitress]
level = INFO
qualname = waitress
handlers =

[logger_pypicloud]
level = INFO
qualname = pypicloud
handlers =

[logger_boto]
level = WARN
qualname = boto
handlers =

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)s %(asctime)s [%(name)s] %(message)s
EOF

exec pserve server.ini "$@"
