#!/bin/bash

# Copy Netscape Communicator nsmail to Evolution mail tree
# Copyright (C) 2004 James Cameron
# Released under the GNU Public License

set -e

function process {

    # sanity check that the directories are present
    if [ ! -d "${1}" ]; then
        echo "process: source directory not found ${1}"
	exit 1
    fi
    if [ ! -d "${2}" ]; then
        echo "process: target directory not found ${2}"
	exit 1
    fi

    # drop into the source, do for each file
    cd "${1}";for file in *; do

        # if there were no files, skip this
        if test "$file" == "*"; then continue; fi

	# adjust the file to include source path
        file="${1}/${file}"

	# process files (which are mbox's)
        if [ -f "${file}" ]; then
	    name="`basename \"${file}\"`"
            echo "${file} is mbox, copy to ${2}/${name}/mbox"
            mkdir -p "${2}/${name}"
            cp "${file}" "${2}/${name}/mbox"
	    echo -e "<?xml version=\"1.0\"?>\n<efolder><type>mail</type><description></description></efolder>\n" > "${2}/${name}/folder-metadata.xml"
            continue
        fi

	# process directories (which are to be subfolders of the mailbox)
        if [ -d "${file}" ]; then
	    name="`basename \"${file}\"`"
	    name="${name/.sbd/}"
	    echo "${file} is folder, recurse to ${name} "

	    # make the subfolders tree for the mailbox
	    mkdir -p "${2}/${name}/subfolders"

	    # recurse into this directory
            process "${file}" "${2}/${name}/subfolders"

	    # remove directories if nothing was created within them
	    test -d "${2}/${name}/subfolders" && \
	        rmdir --ignore-fail-on-non-empty "${2}/${name}/subfolders" || \
		    true
	    test -d "${2}/${name}" && \
	        rmdir --ignore-fail-on-non-empty "${2}/${name}" || \
		    true
            continue
        fi
    done
}

DST=${PWD}/evolution/local
SRC=${PWD}/nsmail

process ${SRC} ${DST}
