#!/bin/bash

if [ $# -ne 1 ]; then
  echo "usage: $0 profilename"
  exit 1
fi

which awk > /dev/null
if [ $? -ne 0 ]; then
  echo "this script requires awk"
  exit 1
fi

set -e

if [ ! -f ~/.mozilla.org/seamonkey/profiles.ini ]; then
  echo "You don't seem to have any old profiles"
  exit 1
fi

profiledir=`awk -v profname=${1} 'BEGIN {found=0} {
        if (found) {
          if (/^Path/) {
            split($0,path,"=");
            print path[2];
            exit;
          }
          if (/^\[Profile/) {
            print "FAIL";
            exit;
          }
        }
        if (/^Name/) {
          split($0,name,"=");
          if (name[2] == profname) {
            found=1;
          }
        }
      }' ~/.mozilla.org/seamonkey/profiles.ini`

if [ -z "$profiledir" ] || [ "$profiledir" = "FAIL" ]; then
  echo "failed to parse profiles.ini"
  exit 1
fi

if [ -f ~/.mozilla.org/seamonkey/"$profiledir" ]; then
  echo "old profile directory does not exist!"
  exit 1
fi

# look for the profile directory in the new location
if [ -d ~/.mozilla/seamonkey ] && [ -f ~/.mozilla/seamonkey/profiles.ini ]; then
  # look in the new profiles.ini
  set +e
  grep "^Name=${1}"'$' ~/.mozilla/seamonkey/profiles.ini > /dev/null
  if [ $? -eq 0 ]; then
    echo "Profile $1 already exists in ~/.mozilla/seamonkey"
    exit 1
  fi
  set -e

  # check the directory too
  if [ -d ~/.mozilla/seamonkey/"$profiledir" ]; then
    echo "profile directory for $1 already exists in ~/.mozilla/seamonkey"
    exit 1
  fi
fi

mkdir -p ~/.mozilla/seamonkey/
cd ~/.mozilla/seamonkey

# fix up profiles.ini

if [ -f profiles.ini ]; then
  profnum=`grep "^\[Profile" profiles.ini | tail -n 1 | sed -e 's#\[Profile\(.*\)\]#\1#'`
  profnum=`expr $profnum + 1`
  # append new section header to profiles.ini
  echo "[Profile${profnum}]" >> profiles.ini
else
  # make a new file.  It's missing a General section, but that's OK.
  echo "[Profile0]" > profiles.ini
fi

# find the appropriate bits from the old profile.ini and append them to the new
# one
awk -v profname=${1} 'BEGIN {found=0} {
        if (found) {
          if (/^\[Profile/) exit;
          print;
        }
        else if (/^Name/) {
          split($0,name,"=");
          if (name[2] == profname) {
            found=1; print;
          }
        }
      }' ~/.mozilla.org/seamonkey/profiles.ini >> profiles.ini

cp -a ~/.mozilla.org/seamonkey/"$profiledir" .
cd "$profiledir"

echo "Adapting paths in profile"
rm -f XUL.mfasl XPC.mfasl panacea.dat xpti.dat compreg.dat
for f in prefs.js user.js extensions.ini secmod.db; do
  if [ -f "$f" ]; then
    perl -pe 's,/\.mozilla\.org/,/.mozilla/,g' -iBAK $f
  fi
done
