define alternc::bureau::account (
  String $mail,
  String $password  = '',
  String $ensure = 'present',
  String $username = $name,
  Boolean $enabled = true,
  Boolean $su = false,
  String $account_type = 'default',
  $creator = 2000, # Usually an integer, but could be 'NULL'
  Integer $db_server_id = 1
) {
  # @TODO: Values containing a single-quote should be escaped
  # @TODO: Maybe it's better to define complicated types in ruby?
  # @TODO: Convert password to sha512cr?
  $mysql_command = '/usr/bin/mysql --defaults-file=/etc/alternc/my.cnf'
  $account_exists = "${mysql_command} -e \"select uid, login from membres where login = '${username}'\\G\" | grep -q 'login: ${username}'"
  $account_add = "${mysql_command} -e \"insert into membres (login, mail, enabled, su, type, creator, db_server_id) VALUES ('${username}', '${mail}', ${enabled}, ${su}, '${account_type}', ${creator}, ${db_server_id});\""
  $account_set = "${mysql_command} -e \"update membres set login = '${username}', mail = '${mail}', enabled = ${enabled}, su = ${su}, type = '${account_type}', creator = ${creator}, db_server_id = ${db_server_id} where login = '${username}'\""
  $account_remove = "${mysql_command} -e \"delete from membres where login = '${username}'\""
  $account_is = "${mysql_command} -e \"select login from membres where login = '${username}' and mail = '${mail}' and enabled = ${enabled} and su = ${su} and type = '${account_type}' and db_server_id = ${db_server_id}\\G\" | grep -q 'login: ${username}'"
  $real_ensure = $ensure ? {
    'absent' => 'absent',
    default  => 'present',
  }

  if $real_ensure == 'present' {
    exec { "alternc_bureau_account_set_${name}":
      command => $account_set,
      unless  => $account_is,
      require => Package['alternc'],
      notify  => Exec["alternc_bureau_account_${name}_set_password"],
    }
    exec { "alternc_bureau_account_add_${name}":
      command => $account_add,
      unless  => $account_exists,
      require => Package['alternc'],
      notify  => Exec["alternc_bureau_account_${name}_set_password"],
    }
    exec { "alternc_bureau_account_${name}_set_password":
      # @see /usr/lib/alternc/alternc-password
      command     => "${mysql_command} -e \"update membres set pass = ENCRYPT('${password}', CONCAT('\\\$1\\\$',MD5('\$RND'))) where login = '${username}'\"",
      refreshonly => true,
    }
  }
  else {
    exec { "alternc_bureau_account_remove_${name}":
      command => $account_remove,
      onlyif  => $account_exists,
      require => Package['alternc'],
    }
  }
}