import os

from django.utils.translation import ugettext_lazy as _

from openstack_dashboard import exceptions

DEBUG = <%= @django_debug.to_s.capitalize %>
TEMPLATE_DEBUG = DEBUG

# WEBROOT is the location relative to Webserver root
# should end with a slash.
WEBROOT = '<%= scope.lookupvar("horizon::params::root_url") %>/'

# Required for Django 1.5.
# If horizon is running in production (DEBUG is False), set this
# with the list of host/domain names that the application can serve.
# For more information see:
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
#ALLOWED_HOSTS = ['horizon.example.com', ]
<% if @final_allowed_hosts.kind_of?(Array) %>
ALLOWED_HOSTS = ['<%= @final_allowed_hosts.join("', '") %>', ]
<% else %>
ALLOWED_HOSTS = ['<%= @final_allowed_hosts %>', ]
<% end %>

# Set SSL proxy settings:
# For Django 1.4+ pass this header from the proxy after terminating the SSL,
# and don't forget to strip it from the client's request.
# For more information see:
# https://docs.djangoproject.com/en/1.4/ref/settings/#secure-proxy-ssl-header
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

# If Horizon is being served through SSL, then uncomment the following two
# settings to better secure the cookies from security exploits
<% if @secure_cookies %>
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
<% else %>
#CSRF_COOKIE_SECURE = True
#SESSION_COOKIE_SECURE = True
<% end %>

# Overrides for OpenStack API versions. Use this setting to force the
# OpenStack dashboard to use a specfic API version for a given service API.
# NOTE: The version should be formatted as it appears in the URL for the
# service API. For example, The identity service APIs have inconsistent
# use of the decimal point, so valid options would be "2.0" or "3".
# OPENSTACK_API_VERSIONS = {
#     "identity": 3
# }

<% if ! (@api_versions.empty?) and  @api_versions.kind_of?(Hash) %>
OPENSTACK_API_VERSIONS = {
<% @api_versions.sort.each do |opt_name,opt_val| -%>
  '<%= opt_name -%>': <%= opt_val -%>,
<%end %>
}
<%end %>

# Set this to True if running on multi-domain model. When this is enabled, it
# will require user to enter the Domain name in addition to username for login.
# OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT = False
<% if @keystone_multidomain_support %>
OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT = True
<% end %>

# Overrides the default domain used when running on single-domain model
# with Keystone V3. All entities will be created in the default domain.
# OPENSTACK_KEYSTONE_DEFAULT_DOMAIN = 'Default'
<% if @keystone_default_domain %>
OPENSTACK_KEYSTONE_DEFAULT_DOMAIN = '<%= @keystone_default_domain %>'
<% end %>

# Set Console type:
# valid options would be "AUTO", "VNC" or "SPICE"
# CONSOLE_TYPE = "AUTO"

# Default OpenStack Dashboard configuration.
HORIZON_CONFIG = {
    'dashboards': ('project', 'admin', 'settings',),
    'default_dashboard': 'project',
    'user_home': 'openstack_dashboard.views.get_user_home',
    'ajax_queue_limit': 10,
    'auto_fade_alerts': {
        'delay': 3000,
        'fade_duration': 1500,
        'types': ['alert-success', 'alert-info']
    },
    'help_url': "<%= @help_url %>",
    'exceptions': {'recoverable': exceptions.RECOVERABLE,
                   'not_found': exceptions.NOT_FOUND,
                   'unauthorized': exceptions.UNAUTHORIZED},
}

# Specify a regular expression to validate user passwords.
# HORIZON_CONFIG["password_validator"] = {
#     "regex": '.*',
#     "help_text": _("Your password does not meet the requirements.")
# }

# Disable simplified floating IP address management for deployments with
# multiple floating IP pools or complex network requirements.
# HORIZON_CONFIG["simple_ip_management"] = False

# Turn off browser autocompletion for the login form if so desired.
# HORIZON_CONFIG["password_autocomplete"] = "off"

LOCAL_PATH = os.path.dirname(os.path.abspath(__file__))

# Set custom secret key:
# You can either set it to a specific value or you can let horizion generate a
# default secret key that is unique on this machine, e.i. regardless of the
# amount of Python WSGI workers (if used behind Apache+mod_wsgi): However, there
# may be situations where you would want to set this explicitly, e.g. when
# multiple dashboard instances are distributed on different machines (usually
# behind a load-balancer). Either you have to make sure that a session gets all
# requests routed to the same dashboard instance or you set the same SECRET_KEY
# for all of them.
# from horizon.utils import secret_key
# SECRET_KEY = secret_key.generate_or_read_from_file(os.path.join(LOCAL_PATH, '.secret_key_store'))
SECRET_KEY = '<%= @secret_key %>'

# We recommend you use memcached for development; otherwise after every reload
# of the django development server, you will have to login again. To use
# memcached set CACHES to something like
# CACHES = {
#    'default': {
#        'BACKEND' : 'django.core.cache.backends.memcached.MemcachedCache',
#        'LOCATION' : '127.0.0.1:11211',
#    }
#}

CACHES = {
    'default': {
    <% if @cache_options.kind_of?(Hash) %>
        'OPTIONS': {
        <% @cache_options.sort.each do |opt_name,opt_val| -%>
        '<%= opt_name -%>': <%= opt_val -%>,
        <% end -%>},
    <% end -%>
    'BACKEND': '<%= @cache_backend %>',
    <% if @cache_server_ip %>
          <% if @cache_server_ip.kind_of?(Array) %>
            <%  split = ":" + @cache_server_port + "','" %>
        'LOCATION': [ <% @cache_server_ip.each do |ip| -%>'<%= ip -%>:<%= @cache_server_port -%>',<% end -%> ],
          <% else %>
        'LOCATION': '<%= @cache_server_ip %>:<%= @cache_server_port %>',
          <% end %>
    <% end %>
    }
}

<% if @django_session_engine %>
SESSION_ENGINE = "<%= @django_session_engine %>"
<% end %>

# Send email to the console by default
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Or send them to /dev/null
#EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'

# Configure these for your outgoing email host
# EMAIL_HOST = 'smtp.my-company.com'
# EMAIL_PORT = 25
# EMAIL_HOST_USER = 'djangomail'
# EMAIL_HOST_PASSWORD = 'top-secret!'

# For multiple regions uncomment this configuration, and add (endpoint, title).
<% if @available_regions.kind_of?(Array) %>
AVAILABLE_REGIONS = [
<% @available_regions.each do |r| -%>
    ('<%= r[0] -%>', '<%= r[1] -%>'),
<% end -%>
]
<% end -%>

OPENSTACK_KEYSTONE_URL = "<%= @keystone_url %>"
OPENSTACK_KEYSTONE_DEFAULT_ROLE = "<%= @keystone_default_role %>"

# Disable SSL certificate checks (useful for self-signed certificates):
# OPENSTACK_SSL_NO_VERIFY = False
<% if @ssl_no_verify %>
OPENSTACK_SSL_NO_VERIFY = True
<% end -%>

# The CA certificate to use to verify SSL connections
# OPENSTACK_SSL_CACERT = '/path/to/cacert.pem'

# The OPENSTACK_KEYSTONE_BACKEND settings can be used to identify the
# capabilities of the auth backend for Keystone.
# If Keystone has been configured to use LDAP as the auth backend then set
# can_edit_user to False and name to 'ldap'.
#
# TODO(tres): Remove these once Keystone has an API to identify auth backend.
OPENSTACK_KEYSTONE_BACKEND = {
    'name': 'native',
    'can_edit_user': True,
    'can_edit_group': True,
    'can_edit_project': True,
    'can_edit_domain': True,
    'can_edit_role': True
}

# The OPENSTACK_HYPERVISOR_FEATURES settings can be used to enable optional
# services provided by hypervisors.
<%- if ! (@hypervisor_options_real.empty?) -%>
OPENSTACK_HYPERVISOR_FEATURES = {
<%- @hypervisor_options_real.sort.each do |opt_name,opt_val| -%>
    '<%= opt_name -%>': <%= opt_val.to_s.capitalize -%>,
<%-end-%>
}
<%-end-%>

# The OPENSTACK_CINDER_FEATURES settings can be used to enable optional
# services provided by cinder that is not exposed by its extension API.
<%- if ! (@cinder_options_real.empty?) -%>
OPENSTACK_CINDER_FEATURES = {
<%- @cinder_options_real.sort.each do |opt_name,opt_val| -%>
    '<%= opt_name -%>': <%= opt_val.to_s.capitalize -%>,
<%-end-%>
}
<%-end-%>

# The OPENSTACK_NEUTRON_NETWORK settings can be used to enable optional
# services provided by neutron. Options currenly available are load
# balancer service, security groups, quotas, VPN service.
# The profile_support option is used to detect if an externa lrouter can be
# configured via the dashboard. When using specific plugins the
# profile_support can be turned on if needed.
<%- if ! (@neutron_options_real.empty?) -%>
OPENSTACK_NEUTRON_NETWORK = {
<%- @neutron_options_real.sort.each do |opt_name,opt_val| -%>
  <%- if opt_val == true or opt_val == false -%>
    '<%= opt_name -%>': <%= opt_val.to_s.capitalize -%>,
  <%- else -%>
    '<%= opt_name -%>': '<%= opt_val -%>',
  <%-end-%>
<%-end-%>
}
<%-end-%>

# The OPENSTACK_IMAGE_BACKEND settings can be used to customize features
# in the OpenStack Dashboard related to the Image service, such as the list
# of supported image formats.
# OPENSTACK_IMAGE_BACKEND = {
#     'image_formats': [
#         ('', ''),
#         ('aki', _('AKI - Amazon Kernel Image')),
#         ('ami', _('AMI - Amazon Machine Image')),
#         ('ari', _('ARI - Amazon Ramdisk Image')),
#         ('iso', _('ISO - Optical Disk Image')),
#         ('qcow2', _('QCOW2 - QEMU Emulator')),
#         ('raw', _('Raw')),
#         ('vdi', _('VDI')),
#         ('vhd', _('VHD')),
#         ('vmdk', _('VMDK'))
#     ]
# }
<%- if !(@image_backend.empty?) -%>
OPENSTACK_IMAGE_BACKEND = {
  <%- @image_backend.each do |opt_name,opt_val| -%>
    '<%= opt_name %>': [
      <%- opt_val.each do |val,label| -%>
        ('<%= val %>', _('<%= label %>')),
      <%- end -%>
    ], # <%= opt_name %>
  <%- end -%>
} # OPENSTACK_IMAGE_BACKEND
<%- end -%>

# OPENSTACK_ENDPOINT_TYPE specifies the endpoint type to use for the endpoints
# in the Keystone service catalog. Use this setting when Horizon is running
# external to the OpenStack environment. The default is 'publicURL'.
#OPENSTACK_ENDPOINT_TYPE = "publicURL"
<% if @openstack_endpoint_type %>
OPENSTACK_ENDPOINT_TYPE = "<%= @openstack_endpoint_type %>"
<% end %>

# SECONDARY_ENDPOINT_TYPE specifies the fallback endpoint type to use in the
# case that OPENSTACK_ENDPOINT_TYPE is not present in the endpoints
# in the Keystone service catalog. Use this setting when Horizon is running
# external to the OpenStack environment. The default is None.  This
# value should differ from OPENSTACK_ENDPOINT_TYPE if used.
#SECONDARY_ENDPOINT_TYPE = "publicURL"
<% if @secondary_endpoint_type %>
SECONDARY_ENDPOINT_TYPE = "<%= @secondary_endpoint_type %>"
<% end %>

# The number of objects (Swift containers/objects or images) to display
# on a single page before providing a paging element (a "more" link)
# to paginate results.
API_RESULT_LIMIT = <%= @api_result_limit %>
API_RESULT_PAGE_SIZE = 20

# The timezone of the server. This should correspond with the timezone
# of your entire OpenStack installation, and hopefully be in UTC.
TIME_ZONE = "UTC"

# If you have external monitoring links, eg:
<% if @horizon_app_links %>
EXTERNAL_MONITORING = <%= @horizon_app_links %>
<% end %>

# When launching an instance, the menu of available flavors is
# sorted by RAM usage, ascending.  Provide a callback method here
# (and/or a flag for reverse sort) for the sorted() method if you'd
# like a different behaviour.  For more info, see
# http://docs.python.org/2/library/functions.html#sorted
# CREATE_INSTANCE_FLAVOR_SORT = {
#     'key': my_awesome_callback_method,
#     'reverse': False,
# }

# CUSTOM_THEME_PATH allows to set to the directory location for the
# theme (e.g., "static/themes/blue"). The path can either be
# relative to the openstack_dashboard directory or an absolute path
# to an accessible location on the file system.
# If not specified, the default CUSTOM_THEME_PATH is
# static/themes/default.
<% if @custom_theme_path %>
CUSTOM_THEME_PATH = '<%= @custom_theme_path %>'
<% end %>

# The Horizon Policy Enforcement engine uses these values to load per service
# policy rule files. The content of these files should match the files the
# OpenStack services are using to determine role based access control in the
# target installation.

# Path to directory containing policy.json files
<% if !(@policy_files_path.nil?) %>
POLICY_FILES_PATH = '<%= @policy_files_path %>'
<% elsif @osfamily == 'RedHat' %>
POLICY_FILES_PATH = '/etc/openstack-dashboard'
<% else %>
#POLICY_FILES_PATH = os.path.join(ROOT_PATH, "conf")
<% end -%>

# Map of local copy of service policy files
<% if @policy_files.kind_of?(Hash) %>
POLICY_FILES = {
<% @policy_files.sort.each do |service_name,filename| -%>
    '<%= service_name -%>': '<%= filename -%>',
<% end -%>
} # POLICY_FILES
<% else -%>
#POLICY_FILES = {
#    'identity': 'keystone_policy.json',
#    'compute': 'nova_policy.json'
#}
<% end -%>

# Trove user and database extension support. By default support for
# creating users and databases on database instances is turned on.
# To disable these extensions set the permission here to something
# unusable such as ["!"].
# TROVE_ADD_USER_PERMS = []
# TROVE_ADD_DATABASE_PERMS = []

LOGGING = {
    'version': 1,
    # When set to True this will disable all logging except
    # for loggers specified in this configuration dictionary. Note that
    # if nothing is specified here and disable_existing_loggers is True,
    # django.db.backends will still log unless it is disabled explicitly.
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(asctime)s %(process)d %(levelname)s %(name)s '
                      '%(message)s'
        },
        'normal': {
            'format': 'dashboard-%(name)s: %(levelname)s %(message)s'
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'django.utils.log.NullHandler',
        },
        'console': {
            # Set the level to "DEBUG" for verbose output logging.
            'level': 'INFO',
            'class': 'logging.StreamHandler',
        },
        'file': {
            'level': '<%= @log_level %>',
            'class': 'logging.FileHandler',
            'filename': '<%= scope.lookupvar("horizon::params::logdir") %>/horizon.log',
            'formatter': 'verbose',
        },
        'syslog': {
            'level': '<%= @log_level %>',
            'facility': 'local1',
            'class': 'logging.handlers.SysLogHandler',
            'address': '/dev/log',
            'formatter': 'normal',
        }
    },
    'loggers': {
        # Logging from django.db.backends is VERY verbose, send to null
        # by default.
        'django.db.backends': {
            'handlers': ['null'],
            'propagate': False,
        },
        'requests': {
            'handlers': ['null'],
            'propagate': False,
        },
        'horizon': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'openstack_dashboard': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'novaclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'cinderclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'keystoneclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'glanceclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'neutronclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'heatclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'ceilometerclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'troveclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'swiftclient': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'openstack_auth': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'nose.plugins.manager': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
        'django': {
            # 'handlers': ['console'],
            'handlers': ['<%= @log_handler %>'],
            # 'level': 'DEBUG',
            'level': '<%= @log_level %>',
            'propagate': False,
        },
    }
}

SECURITY_GROUP_RULES = {
    'all_tcp': {
        'name': 'ALL TCP',
        'ip_protocol': 'tcp',
        'from_port': '1',
        'to_port': '65535',
    },
    'all_udp': {
        'name': 'ALL UDP',
        'ip_protocol': 'udp',
        'from_port': '1',
        'to_port': '65535',
    },
    'all_icmp': {
        'name': 'ALL ICMP',
        'ip_protocol': 'icmp',
        'from_port': '-1',
        'to_port': '-1',
    },
    'ssh': {
        'name': 'SSH',
        'ip_protocol': 'tcp',
        'from_port': '22',
        'to_port': '22',
    },
    'smtp': {
        'name': 'SMTP',
        'ip_protocol': 'tcp',
        'from_port': '25',
        'to_port': '25',
    },
    'dns': {
        'name': 'DNS',
        'ip_protocol': 'tcp',
        'from_port': '53',
        'to_port': '53',
    },
    'http': {
        'name': 'HTTP',
        'ip_protocol': 'tcp',
        'from_port': '80',
        'to_port': '80',
    },
    'pop3': {
        'name': 'POP3',
        'ip_protocol': 'tcp',
        'from_port': '110',
        'to_port': '110',
    },
    'imap': {
        'name': 'IMAP',
        'ip_protocol': 'tcp',
        'from_port': '143',
        'to_port': '143',
    },
    'ldap': {
        'name': 'LDAP',
        'ip_protocol': 'tcp',
        'from_port': '389',
        'to_port': '389',
    },
    'https': {
        'name': 'HTTPS',
        'ip_protocol': 'tcp',
        'from_port': '443',
        'to_port': '443',
    },
    'smtps': {
        'name': 'SMTPS',
        'ip_protocol': 'tcp',
        'from_port': '465',
        'to_port': '465',
    },
    'imaps': {
        'name': 'IMAPS',
        'ip_protocol': 'tcp',
        'from_port': '993',
        'to_port': '993',
    },
    'pop3s': {
        'name': 'POP3S',
        'ip_protocol': 'tcp',
        'from_port': '995',
        'to_port': '995',
    },
    'ms_sql': {
        'name': 'MS SQL',
        'ip_protocol': 'tcp',
        'from_port': '1433',
        'to_port': '1433',
    },
    'mysql': {
        'name': 'MYSQL',
        'ip_protocol': 'tcp',
        'from_port': '3306',
        'to_port': '3306',
    },
    'rdp': {
        'name': 'RDP',
        'ip_protocol': 'tcp',
        'from_port': '3389',
        'to_port': '3389',
    },
}

LOGIN_URL = '<%= scope.lookupvar("horizon::params::root_url") %>/auth/login/'
LOGOUT_URL = '<%= scope.lookupvar("horizon::params::root_url") %>/auth/logout/'
LOGIN_REDIRECT_URL = '<%= scope.lookupvar("horizon::params::root_url") %>'

# The Ubuntu package includes pre-compressed JS and compiled CSS to allow
# offline compression by default.  To enable online compression, install
# the python-lesscpy package and disable the following option.
COMPRESS_OFFLINE = <%= @compress_offline.to_s.capitalize %>

# For Glance image upload, Horizon uses the file upload support from Django
# so we add this option to change the directory where uploaded files are temporarily
# stored until they are loaded into Glance.
FILE_UPLOAD_TEMP_DIR = '<%= @file_upload_temp_dir %>'

<% if @tuskar_ui %>
IRONIC_DISCOVERD_URL = "<%= @tuskar_ui_ironic_discoverd_url %>"
UNDERCLOUD_ADMIN_PASSWORD = "<%= @tuskar_ui_undercloud_admin_password %>"
DEPLOYMENT_MODE = "<%= @tuskar_ui_deployment_mode %>"
<% end %>
