#!/bin/bash

vmailDir="/var/vmail"
tmpDomainList=$(ls ${vmailDir})
mailDomains=()
tmpMailList=()
statValues=()
confDir="/opt/cron_script"

get_domains() {
	for domain in ${tmpDomainList[@]}; do
		#mailDomains+=("$domain")
		if [ "$domain" != "mailboxes" ] && [ "$domain" != "sieve" ]; then
			mailDomains+=($domain)
		fi
	done
}

function insertQuery(){
	local IFS=','
	
	mariadb --defaults-file=${confDir}/.mailstats.cnf \
		--skip-column-names \
		--silent \
		--execute \
		"INSERT INTO stats(node, domain, user, size) VALUES ${statValues[*]};"
}

get_mail_list() {
	tmpMailList=$(ls ${vmailDir}/$1)
}

get_stats() {
	statValues+=(\(\'$(hostname)\',\'$1\',\'$2\',$(du --bytes --summarize "${vmailDir}/${1}/${2}" | awk '{print $1}')\))
}

get_domains

for  domain in ${mailDomains[@]}; do
	statValues=()
	get_mail_list $domain
	for user in ${tmpMailList[@]}; do
		get_stats $domain $user
	done
	
	insertQuery ${statValues}
done
