"""
Django settings for get2unix project.

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

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

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

import os, sys, ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType

try:
    import ConfigParser as conf
except ImportError as e:
    import configparser as conf

# RUNNING_ENV = 'poc'
RUNNING_ENV = 'dev'


##########################
#    Genreal Settings    #
##########################
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
TMP_DIR = os.path.join(BASE_DIR, 'tmp')
# Add search path for apps
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'h42=kn=%%!w9d2olk#3b8#9)8v#6*(49j!6_)-+jre9+n**eh-'

DATA_UPLOAD_MAX_NUMBER_FIELDS = None

ALLOWED_HOSTS = ["*"]

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


##########################
#   Customize Settings   #
##########################
# init config loader
config = conf.ConfigParser()
# load config
if RUNNING_ENV == 'dev':
    if sys.platform == 'darwin':
        config.read(os.path.join(BASE_DIR, 'conf/settings-mac.ini'))
    elif sys.platform == 'linux':
        config.read(os.path.join(BASE_DIR, 'conf/settings-linux.ini'))
    else:
        config.read(os.path.join(BASE_DIR, 'conf/settings-win.ini'))
    DEBUG = True
elif RUNNING_ENV == 'poc':
    config.read(os.path.join(BASE_DIR, 'conf/settings-poc.ini'))
    DEBUG = True

VC_LIST = [x[1:-1] for x in config.get('vcenter', 'list')[1:-1].split(', ')]
VC_CACHE_DB = {}
for vc in VC_LIST:
    VC_CACHE_DB[vc] = config.get('redis', vc)

SVC_ACCOUNT = [config.get('security', 'serviceaccount'), config.get('security', 'servicepassword')]

##########################
#  Application Settings  #
##########################

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_celery_results',
    'django_celery_beat',
    'get2unix',
    'api',
    'security',
    'vmware',
]

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

ASGI_APPLICATION = 'get2unix.routing.application'
WSGI_APPLICATION = 'get2unix.wsgi.application'

ROOT_URLCONF = 'get2unix.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        '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',
            ],
        },
    },
]


##########################
#    Database Settings   #
##########################
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': config.get('db', 'database'),
        'USER': config.get('db', 'user'),
        'PASSWORD': config.get('db', 'password'),
        'HOST': config.get('db', 'host'),
        'PORT': config.getint('db', 'port'),
    }
}

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'TIMEOUT': config.get('redis', 'timeout'),
        'LOCATION': 'redis://' + config.get('redis', 'host') + ':' + config.get('redis', 'port'),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "PASSWORD": config.get('redis', 'password'),
        },
    },
}

TOKEN = config.get('security', 'token')
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_COOKIE_NAME = "sessionid"
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_HTTPONLY = False
SESSION_COOKIE_AGE = 604800


##########################
#    Celery Settings     #
##########################
CELERY_BROKER_URL = 'redis://' + ':' + config.get('redis', 'password') + '@' + config.get('redis', 'host') + ':' +\
                    config.get('redis', 'port') + '/' + config.get('redis', 'celery_db')  # Broker配置，使用Redis作为消息中间件
# CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/2'  # BACKEND配置，这里使用redis
# CELERY_RESULT_SERIALIZER = 'json'  # 结果序列化方案
CELERY_RESULT_BACKEND = 'django-db'
CELERY_CACHE_BACKEND = 'django-cache'


##########################
# Authentication Settings#
##########################
# Password validation
# https://docs.djangoproject.com/en/3.0/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',
    },
]

if config.get('ldap', 'enable') != 'false':
    AUTHENTICATION_BACKENDS = (
        'django_auth_ldap.backend.LDAPBackend',   # ldap
        'django.contrib.auth.backends.ModelBackend',
    )

    # LDAP settings
    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
    AUTH_LDAP_SERVER_URI = 'ldaps://' + config.get('ldap', 'server')
    AUTH_LDAP_BIND_DN = config.get('ldap', 'bind_dn')
    AUTH_LDAP_BIND_PASSWORD = config.get('ldap', 'bind_password')

    AUTH_LDAP_USER_SEARCH = LDAPSearch(
        config.get('ldap', 'search_dn'),
        ldap.SCOPE_SUBTREE,
        '(uid=%(user)s)',
    )

    AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
        config.get('ldap', 'search_group'),
        ldap.SCOPE_SUBTREE,
        '(objectClass=groupOfNames)',
    )

    AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn')
    #AUTH_LDAP_REQUIRE_GROUP = 'cn=itnix,ou=netgroup,dc=its,dc=ebay,dc=com'
    AUTH_LDAP_USER_ATTR_MAP = {
        'first_name': 'givenName',
        'last_name': 'sn',
        'email': 'mail',
    }


##########################
#    Logging Settings    #
##########################

BASE_LOG_DIR = os.path.join(BASE_DIR, "log")

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d]' + \
                  '[task_id:%(name)s][%(filename)s:%(lineno)d] ' + \
                  '[%(levelname)s]- %(message)s'
if config.get('ldap', 'enable') != 'false':
    LDAP_LOGS = os.path.join(BASE_DIR, 'logs/ldap.log')
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {  # 详细
                'format': standard_format
            },
        },
        'handlers': {
            'default': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': LDAP_LOGS,
                'maxBytes': 1024 * 1024 * 100,  # 5 MB
                'backupCount': 5,
                'formatter': 'standard',
            },
            'console': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
            }
        },
        'loggers': {
            '': {  # default日志，存放于log中
                'handlers': ['default'],
                'level': 'INFO',
            },
            'django_auth_ldap': {  # django_auth_ldap模块相关日志打印到console
                'handlers': ['console'],
                'level': 'INFO',
                'propagate': False,  # 选择关闭继承，不然这个logger继承自默认，日志就会被记录2次了(''一次，自己一次)
            },
        }
    }


##########################
#    Common Settings     #
##########################
G2U_HOST = config.get('common', 'g2u_host')

##########################
#      AWX Settings      #
##########################
AWX_URL = config.get('awx', 'awx_api')
AWX_USERNAME = config.get('awx', 'awx_username')
AWX_PASSWORD = config.get('awx', 'awx_password')
AWX_CLIENT_ID = config.get('awx', 'awx_client_id')
AWX_CLIENT_SECERT = config.get('awx', 'awx_client_secret')
AWX_ORG_NAME = config.get("awx", 'awx_org_name')
AWX_INV_PREFIX = config.get('awx', 'awx_inv_prefix')
AWX_INV_DESC = config.get('awx', 'awx_inv_desc')
AWX_SUDO_TEMPLATE = config.get('awx', 'awx_sudo_template')
AWX_COLLECTOR_TEMPLATE = config.get('awx', 'awx_collector_template')
AWX_VULSSCAN_TEMPLATE = config.get('awx', 'awx_vulsscan_template')

##########################
#     VULS Settings      #
##########################
VULS_PATH = config.get('vulsscan', 'vuls_path')
VULS_REPORT_PATH = VULS_PATH + "/results"
VULS_CONF_PATH = config.get('vulsscan', 'conf_path')
VULS_HOST = config.get('vulsscan', 'vuls_host')

##########################
#     SUDO Settings      #
##########################
SUDO_EXCLUDE_USERS = [x[1:-1] for x in config.get('sudo', 'exclude_users')[1:-1].split(', ')]
SUDO_EXCLUDE_GROUPS = [x[1:-1] for x in config.get('sudo', 'exclude_groups')[1:-1].split(', ')]

##########################
#   Terraform Settings   #
##########################
TF_BIN = config.get('terraform', 'tf_bin')
TF_BASE = config.get('terraform', 'tf_base')