#!/usr/bin/ruby
#
# NAME
#
#  sympl-mail-encrypt-passwords - Automatic hashing for user passwords
#
# SYNOPSIS
#
#  sympl-mail-encrypt-passwords [ -h | --help ] [-m | --manual] [ -v | --verbose ]
#
# OPTIONS
#
#  -v, --verbose         Show verbose messages
#
#  -h, --help            Show a help message, and exit.
#
#  -m, --manual          Show this manual, and exit.
#
# Passwords that are already encrypted will remain unaltered.
#
# AUTHOR
#
# David Edwards <david.edwards@bytemark.co.uk>
#

require 'getoptlong'

manual = help = false
opts = GetoptLong.new(
         [ '--help',       '-h', GetoptLong::NO_ARGUMENT ],
         [ '--manual',     '-m', GetoptLong::NO_ARGUMENT ],
         [ '--verbose',    '-v', GetoptLong::NO_ARGUMENT ]
       )

opts.each do |opt,arg|
  case opt
  when '--help'
    help = true
  when '--manual'
    manual = true
  when '--verbose'
    $VERBOSELOCAL = true
  end
end

#
# Output help as required.
#
if help or manual
  require 'symbiosis/utils'
  Symbiosis::Utils.show_help(__FILE__) if help
  Symbiosis::Utils.show_manual(__FILE__) if manual
  exit 0
end

#
# Require these bits here, so we can generate the manpage without needing extra
# build-deps.
#

require 'symbiosis/utils'
require 'symbiosis/domains'
require 'symbiosis/domain/mailbox'

Symbiosis::Domains.each do |domain|
  #
  # Skip domains without email password auto encryption.
  #
  unless domain.should_encrypt_mailbox_passwords?
    puts "** #{domain.name} has not had email password auto encryption enabled.  Skipping." if $VERBOSELOCAL
    next
  end

  puts "-> #{domain.name}" if $VERBOSELOCAL

  domain.mailboxes.each do |box|

    #
    # We can't do anything with passwords that are not strings.
    #
    unless box.password.is_a?(String)
      puts "   ** #{box.local_part}: No password has been set.  Skipping." if $VERBOSELOCAL
      next
    end

    #
    # Don't need to crypt passwords that are already crypt'd
    #
    if domain.crypt_password(box.password) == box.password
      puts "   ** #{box.local_part}: Password is already hashed. Skipping" if $VERBOSELOCAL
      next
    end

    puts "   -> #{box.local_part}: Hashing password." if $VERBOSELOCAL
    box.password = box.password
  end
end
