#!/bin/bash

#
# Builds a list of calendar names for each user account and writes
# them to STDOUT in this format:
#
# account,calendar1,calendar2,calendar3... etc
#
# If you want to write to a file then redirect output:
#
#     build-calendar-list.sh [domain] > /path/to/file
#
# This file can then be used to feed to the migrate-zimbra.php script
#
# Usage: get-user-data.sh [domain]
#
#    [domain] Domain to get data for (if not given data is fetched for all domains)
# 
# @author Brad Kowalczyk <brad@staff.atmail.com>
# @copyright Brad Kowalczyk <brad@staff.atmail.com>
#

# Set to the path of your zimbra CLI tools
zmBin="/opt/zimbra/bin";

if [ $1 ]
then
    domains="$1"
else
    # If no domain given then fetch data for all domains
    domains=`$zmBin/zmprov gad`
fi

# Loop through domains
for d in $domains
do
    accounts=`$zmBin/zmprov -l gaa "$d"`

    for a in $accounts
    do
        echo "Acc: $a"
        folders=`$zmBin/zmprov sm "$a" gaf`
        calendars=`echo "$folders" | grep -e "^ \+[0-9]\+ \+appo \+[0-9]\+ \+[0-9]\+ \+/"`

        # Strip out the everything but the calendar name
        calendars=`echo "$calendars" | sed -ne "s/^ \+[0-9]\+ \+appo \+[0-9]\+ \+[0-9]\+ \+\//Cal: /p"`
        #calendars=`echo $calendars | sed -ne "s/ /:appo,/p"`
        echo "$calendars"

        contactFolders=`echo "$folders" | grep -e "^ \+[0-9]\+ \+cont \+[0-9]\+ \+[0-9]\+ \+/"`

        # Strip out the everything but the calendar name
        contactFolders=`echo "$contactFolders" | sed -ne "s/^ \+[0-9]\+ \+cont \+[0-9]\+ \+[0-9]\+ \+\//Con: /p"`
        #contactFolders=`echo $contactFolders | sed -ne "s/ /:cont,/"`
        echo "$contactFolders"
    done
done

