An AddressBook to SquirrelMail script

Aug 03, '04 09:11:00AM

Contributed by: jecwobble

I wrote a shell script to convert home and work email addresses from AddressBook into SquirrelMail's abook format. It's my first real shell script and could likely be improved upon (note the TODO). I'd appreciate any comments and especially hope someone else finds this useful. It's not extensively tested, and you should back up any existing abook files before running it (again note the TODO).

It's free to use and modify to your heart's content (like removing the need to run as root, so individual users can run it for themselves -- I have it cron'd for my wife and I). If you make significant changes, all I ask is that you please post them in the comments for others to use and learn from.

The script requires the contacts command line utility and of course SquirrelMail. The two grep lines following the sudo lines are split for width, but should be on the same line as the preceding sudo.

#!/bin/sh

#   to be run as root (manually or with cron)
#   pass one or more user's names as arguments
#
#   Requires:
#     /usr/local/bin/contacts @ http://gnufoo.org/contacts/
#     SquirrelMail @ http://www.squirrelmail.org/
#
#   TODO: make option to merge with existing abook instead of overwriting

# Change the following to your SquirrelMail data directory
sm_data_path="/var/squirrelmail/data/"
E_NOARGS=65
valid_users=0
invalid_users=0

if [ "$(/usr/bin/whoami)" != "root" ] ; then
  echo "`basename $0`: You must be root to run this command." >&2
  exit 1
fi 

if [ ! -n "$1" ]; then
  echo "Usage: `basename $0` username1 username2 etc."
  exit $E_NOARGS
fi

for arg in "$@"; do
  if nireport . /users name | sed 's/[^[:alnum:]]//g' | grep "^$arg$" ; then
    # valid user- perform abook update
    let "valid_users+=1"
    sudo -u $arg /usr/local/bin/contacts -HsS -f "%fn-%ln-home|%fn|%ln|%he|" | 
/usr/bin/grep -v "||" > /tmp/${arg}.abook
    sudo -u $arg /usr/local/bin/contacts -HsS -f "%fn-%ln-work|%fn|%ln|%we|" | 
/usr/bin/grep -v "||" >> /tmp/${arg}.abook
    /bin/mv /tmp/${arg}.abook ${sm_data_path}
    /usr/sbin/chown www:www ${sm_data_path}${arg}.abook
  else
    # not a valid user
    echo "`basename $0`: $user is not a valid user" >&2
    let "invalid_users+=1"
  fi
done

echo "${valid_users} valid user's were processed."
echo "${invalid_users} invalid user's were skipped."

exit 0
[robg adds: I haven't tested this one...]

Comments (3)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20040802151228736