#!/bin/bash
#
# qmail_copy_queue.sh (ver. 0.3) - Copy qmail messages from an old queue to a newest installed qmail
# 
#  By Phil2k@gmail.com
#

if [ "$#" -lt 1 ]; then
 echo -e "$0 <old_var_qmail_queue> [<new_qmail-inject_path>]\nWhere: <old_var_qmail_queue> = path to an old /var/qmail/queue\n       <new_qmail-inject_path> = path to executabile qmail-inject of new qmail-queue (default: /var/qmail/bin/qmail-inject)\n" >&2
 exit 1
fi

old_queue="$1"
qmail_inject="$2"
if [ -z "$qmail_inject" -o ! -x "$qmail_inject" ]; then
 qmail_inject="/var/qmail/bin/qmail-inject"
fi

find $old_queue/mess -type f|while read file; do
 mess=`basename $file`
 p=`dirname $file`
 dir=`basename $p`
 rcpts=""
 if [ -e old_queue/info/$dir/$mess ]; then
  from=`cat $old_queue/info/$dir/$mess|cut -c2-|tr '\0' ''`
 elif [ -e old_queue/info/$mess ]; then
  from=`cat $old_queue/info/$mess|cut -c2-|tr '\0' ''`
 else
  from=""
 fi
 if [ -e $old_queue/remote/$dir/$mess ]; then # it's for remote delivery
  rcpts=`cat $old_queue/remote/$dir/$mess|cut -c2-|tr '\0' ' '`
  echo "REMOTE: $dir/$mess ($from -> $rcpts)"
 elif [ -e $old_queue/remote/$mess ]; then # it's for remote delivery
  rcpts=`cat $old_queue/remote/$mess|cut -c2-|tr '\0' ' '`
  echo "REMOTE: $mess ($from -> $rcpts)"
 elif [ -e $old_queue/local/$dir/$mess ]; then # it's for local delivery
  rcpts=`cat $old_queue/local/$dir/$mess|cut -c2-|tr '\0' ' '`
  echo "LOCAL: $dir/$mess ($from -> $rcpts)"
 elif [ -e $old_queue/local/$mess ]; then # it's for local delivery
  rcpts=`cat $old_queue/local/$mess|cut -c2-|tr '\0' ' '`
  echo "LOCAL: $mess ($from -> $rcpts)"
 else
  echo "Mess [$dir/]$mess not found in local/remote of $old_queue !" >&2
 fi
 if [ -n "$rcpts" ]; then
  cmd="$qmail_inject -a -f $from $rcpts < $old_queue/mess/$dir/$mess"
  echo "Execute: $cmd"
  $cmd
 fi
done