# == Class: gnocchi::db
#
#  Configure the Gnocchi database
#
# === Parameters
#
# [*database_connection*]
#   Url used to connect to database.
#   (Optional) Defaults to 'sqlite:////var/lib/gnocchi/gnocchi.sqlite'.
#
# [*package_ensure*]
#   (optional) The state of gnocchi packages
#   Defaults to 'present'
#
# DEPRECATED PARAMETERS
#
# [*ensure_package*]
#   (optional) The state of gnocchi packages
#   Defaults to undef
#
class gnocchi::db (
  $database_connection = 'sqlite:////var/lib/gnocchi/gnocchi.sqlite',
  $package_ensure      = 'present',
  # DEPRECATED PARAMETERS
  $ensure_package      = undef,
) inherits gnocchi::params {

  include ::gnocchi::deps

  if $ensure_package {
    warning("gnocchi::db::ensure_package is deprecated and will be removed in \
the future release. Please use gnocchi::db::package_ensure instead.")
    $package_ensure_real = $ensure_package
  } else {
    $package_ensure_real = $package_ensure
  }

  # NOTE(spredzy): In order to keep backward compatibility we rely on the pick function
  # to use gnocchi::<myparam> if gnocchi::db::<myparam> isn't specified.
  $database_connection_real = pick($::gnocchi::database_connection, $database_connection)

  validate_re($database_connection_real,
    '^(sqlite|mysql(\+pymysql)?|postgresql):\/\/(\S+:\S+@\S+\/\S+)?')

  if $database_connection_real {
    case $database_connection_real {
      /^mysql(\+pymysql)?:\/\//: {
        require '::mysql::bindings'
        require '::mysql::bindings::python'
        if $database_connection_real =~ /^mysql\+pymysql/ {
          $backend_package = $::gnocchi::params::pymysql_package_name
        } else {
          $backend_package = false
        }
      }
      /^postgresql:\/\//: {
        $backend_package = false
        require '::postgresql::lib::python'
      }
      /^sqlite:\/\//: {
        $backend_package = $::gnocchi::params::sqlite_package_name
      }
      default: {
        fail('Unsupported backend configured')
      }
    }

    if $backend_package and !defined(Package[$backend_package]) {
      package {'gnocchi-backend-package':
        ensure => present,
        name   => $backend_package,
        tag    => 'openstack',
      }
    }

    gnocchi_config {
      'indexer/url': value => $database_connection_real, secret => true;
    }

    # NOTE(tobasco): gnocchi-indexer-sqlalchemy not packaged in Ubuntu for Queens release.
    if $::osfamily != 'Debian' {
      package { 'gnocchi-indexer-sqlalchemy':
        ensure => $package_ensure_real,
        name   => $::gnocchi::params::indexer_package_name,
        tag    => ['openstack', 'gnocchi-package'],
      }
    }
  }

}
