#!/bin/sh

# Brendan Kehoe - brendan@zen.org
# v0.90 2005-01-24

# Given a tree of kmail's maildir, adjust a copy of it
# so courier-imapd will like it.

src=$HOME/mail
dest=$HOME/Maildir

## Find every directory that matters.

# We pipe into a while loop so we can make sure to handle
# any folders that have spaces in their names.

(cd "${src}" ; find . -name cur ) | \
  while read d ; do
    d=`echo "${d}" | sed -e s,/cur,,`

    case "${d}" in
        # Change .foo.directory into just .foo
	*.directory)
	  top=`echo "${d}" | sed -e s,.directory\$,,`
	  ;;
        # Change .foo.directory/bar into .foo.bar
	*.directory/*)
	  top=`echo "${d}" | sed -e s,.directory/,.,`
	  ;;
        # Put the inbox cur/new/tmp at the top of the IMAP dir
    ./inbox/*)
      top=.
      ;;
        # Change ./foo into .foo
	./*)
	  top=`echo "${d}" | sed -e s,./,.,`
	  ;;
	*.*)
	  echo "$0: WARNING: folder ${d} will have problems with a dot in the name"
	  ;;
    esac
    if [ -f "${dest}/${top}" ]; then
      echo "$0: ERROR: ${parent} exists as a file"
      continue
    fi
    if [ ! -d "${src}/${d}/cur" ]; then
      echo "$0: ERROR: ${src}/${d} has no cur subdir -- delete it?"
      continue
    fi

    test -d "${dest}/${top}/." && continue

    echo "${dest}/${top}"
    mkdir "${dest}/${top}"

    # Make sure to only get the parts of the folder we
    # are working on, not any sub-folders.
    ( cd "${src}/${d}" ; tar cf - cur tmp new ) | \
      ( cd "${dest}/${top}" ; tar xf - )

  done

