"""
Django settings for rvusite project.

Generated by 'django-admin startproject' using Django 1.9.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/

----

https://docs.djangoproject.com/en/1.9/intro/tutorial04/
https://docs.djangoproject.com/en/1.9/ref/request-response/
http://django-tables2.readthedocs.org/en/latest/pages/tutorial.html
https://github.com/burke-software/django-report-builder/blob/master/docs/quickstart.md
http://www.marinamele.com/taskbuster-django-tutorial/install-and-configure-mysql-for-django
#https://github.com/gtaylor/django-dynamodb-sessions
http://docs.aws.amazon.com/codedeploy/latest/userguide/how-to-run-agent.html#how-to-run-agent-update-ubuntu

BIGGIE!
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-prereq
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html
http://stackoverflow.com/questions/21764319/django-admin-py-and-python-path-on-ec2-amazon-beanstalk
https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/
https://rickchristianson.wordpress.com/2013/10/31/getting-a-django-app-to-use-https-on-aws-elastic-beanstalk/


http://go-to-hellman.blogspot.com/2015/11/using-lets-encrypt-to-secure-elastic.html

openssl genrsa -out my-private-key.pem 2048
openssl req -sha256 -new -key my-private-key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey my-private-key.pem -out my-certificate.pem
aws iam upload-server-certificate --server-certificate-name rvu-server-cert   \
   --certificate-body file://my-certificate.pem --private-key file://my-private-key.pem
#aws iam upload-server-certificate --server-certificate-name rvu-server-cert  \
#    --certificate-body file://my-certificate.pem --private-key file://my-private-key.pem \
#    --certificate-chain file://my-certificate-chain.pem

aws iam upload-server-certificate --server-certificate-name my-server-cert --certificate-body file://server.crt  --private-key file://privatekey.pem

http://stackoverflow.com/questions/27552859/aws-elastic-beanstalk-logging-with-python-django

sudo pip install django boto
#sudo pip install django-tables2 numpy pandas django-pandas
sudo pip install django-report-builder mysqlclient
sudo pip install django-dynamodb-sessions django-braces
sudo pip install awscli awsebcli coverage
sudo pip install selenium pyyaml django-nose django-crispy-forms

sudo apt-get install python-pip python-dev mariadb-server libmysqlclient-dev
sudo apt-get install ruby2.0
sudo mysql_secure_installation

aws s3 cp s3://aws-codedeploy-us-east-1/latest/install . --region region-name
chmod +x ./install
sudo ./install auto

create database rvu character set utf8;
#CREATE USER rvuuser@localhost IDENTIFIED BY 'changmenow';
CREATE USER rvuuser@'%' IDENTIFIED BY 'changmenow';
#GRANT ALL PRIVILEGES ON rvu.* TO rvuuser@localhost;
GRANT ALL PRIVILEGES ON rvu.* TO rvuuser@'%';

GRANT ALL PRIVILEGES ON rvu.* TO rvuuser;
SET password for rvuuser@'%' = PASSWORD('changemenow');
FLUSH PRIVILEGES;

python manage.py check
python manage.py migrate
python manage.py createsuperuser

python manage.py makemigration rvu
python manage.py migrate rvu

"""

import sys
import os
import json
import boto
import boto.s3
import random

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print "BASE_DIR: %s" % BASE_DIR
region = os.environ.get("REGION", "us-east-1")
bucket_name = os.environ.get("S3_BUCKET_NAME", "")
CONFIG_FILE = os.environ.get("CONFIG_FILE", "/etc/rvu/config.json")

# if the config file doesn't exist
# and we're not running unit tests
# grab it from s3
configuration = {}
if "test" in sys.argv or os.environ.get("RVUTEST") or os.uname()[0] == 'Darwin':
    configuration = {
    "django": {
        "DATABASES": {
            "default": {
                "ENGINE": "django.db.backends.sqlite3",
                "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
            }
        },
        "SECRET_KEY": ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]),
        "use_ssl": False,
    }
}
else:
    if not os.path.exists(CONFIG_FILE):
        #os.makedirs(os.path.dirname(CONFIG_FILE))
        s3conn = boto.s3.connect_to_region(region)
        bucket = s3conn.get_bucket(bucket_name)
        k = bucket.get_key(CONFIG_FILE)
        configuration = json.loads(k.get_contents_as_string())
    else:
        configuration = json.load(file(CONFIG_FILE))


STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
#    '/var/www/static/',
]

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = configuration['django']['SECRET_KEY']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG') == "True"

if configuration['django']['use_ssl']:
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_SSL_REDIRECT = True
    SECURE_FRAME_DENY = True
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    CSRF_COOKIE_HTTPONLY = True
    X_FRAME_OPTIONS = "DENY"
    SECURE_HSTS_SECONDS = 3600
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True

# Use nose to run all tests
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

# Tell nose to measure coverage on the 'foo' and 'bar' apps
NOSE_ARGS = [
    '--with-coverage',
    '--cover-package=rvu',
    '--cover-html'
]

CRISPY_TEMPLATE_PACK = 'bootstrap3'

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'rvu.apps.RvuConfig',
    'crispy_forms',
    'django_tables2',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'report_builder',
    'django_nose',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'rvusite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.static',
                'django.template.context_processors.media',
            ],
        },
    },
]

WSGI_APPLICATION = 'rvusite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = configuration['django']['DATABASES']




# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]



# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'EST5EDT'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "..", "static")

