#!/bin/sh

# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "MPL"); you may not use this file
# except in compliance with the MPL. You may obtain a copy of
# the MPL at http://www.mozilla.org/MPL/
#
# Software distributed under the MPL is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the MPL for the specific language governing
# rights and limitations under the MPL.
#
# The Original Code is Enigmail.
#
# The Initial Developer of the Original Code is Patrick Brunschwig.
# Portions created by Patrick Brunschwig <patrick.brunschwig@gmx.net> are
# Copyright (C) 2004 Patrick Brunschwig. All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License (the "GPL"), in which case
# the provisions of the GPL are applicable instead of
# those above. If you wish to allow use of your version of this
# file only under the terms of the GPL and not to allow
# others to use your version of this file under the MPL, indicate
# your decision by deleting the provisions above and replace them
# with the notice and other provisions required by the GPL.
# If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.

#
# This script generates the Enigmail XPI
#

echo "genxpi: Generating $1 in $5"

if [ $# -lt 8 ]; then
  echo "Wrong number of parameters"
  exit 1
fi

xpiFile=$1
xpiVersion="$2"
platform=$3
mozApp=$4
srcDir=$6
xpiModule=$7
dllSuffix=$8
libPrefix=$9
cwd=`pwd`
cd "$5"
targetDir=`pwd`
cd "$cwd"

# Prepare chrome.manifest
cat  ${srcDir}/package/chrome.manifest > ${targetDir}/chrome.manifest

# Pepare install.rdf
sed 's/<!-- targetPlatform placeholder -->/<em:targetPlatform>'${platform}'<\/em:targetPlatform>/' < ${srcDir}/package/install.rdf > ${targetDir}/install.rdf.t1

# Prepare install.js

cat <<EOT > ${targetDir}/install.js
// Install script for Enigmail

var err;
const APP_VERSION=${xpiVersion}.0";


const ABI_PLATFORM_LINUX="Linux_x86-gcc3";
const ABI_PLATFORM_WIN="WINNT_x86-msvc";
const ABI_PLATFORM_DARWIN_PPC="Darwin_ppc-gcc3";
const ABI_PLATFORM_DARWIN_X86="Darwin_x86-gcc3";

const APP_PLATFORM_LINUX="linux";
const APP_PLATFORM_WIN="win";
const APP_PLATFORM_MAC="mac";
const APP_PLATFORM_OTHER="other";


// this function verifies disk space in kilobytes
function verifyDiskSpace(dirPath, spaceRequired) {
  var spaceAvailable;

  // Get the available disk space on the given path
  spaceAvailable = fileGetDiskSpaceAvailable(dirPath);

  // Convert the available disk space into kilobytes
  spaceAvailable = parseInt(spaceAvailable / 1024);

  // do the verification
  if(spaceAvailable < spaceRequired) {
    logComment("Insufficient disk space: " + dirPath);
    logComment("  required : " + spaceRequired + " K");
    logComment("  available: " + spaceAvailable + " K");
    return false;
  }

  return true;
}

// OS type detection
// which platform?
function getPlatform() {
  var platformStr;
  var platformNode = "";

  if('platform' in Install) {
    platformStr = new String(Install.platform);

    if (!platformStr.search(/^Macintosh/))
      platformNode = APP_PLATFORM_MAC;
    else if (!platformStr.search(/^Win/))
      platformNode = APP_PLATFORM_WIN;
    else if (platformStr.search(/Linux/))
      platformNode = APP_PLATFORM_LINUX;
    else
      platformNode = APP_PLATFORM_OTHER;
  }

  return platformNode;
}

err = initInstall("Enigmail v"+APP_VERSION,  // name for install UI
                  "/enigmail",               // registered name
                  APP_VERSION);              // package version

logComment("initInstall: " + err);

var srDest = 500;       // Disk space required for installation (KB)

var fProgram    = getFolder("Program");
logComment("fProgram: " + fProgram);

if (!verifyDiskSpace(fProgram, srDest)) {
  cancelInstall(INSUFFICIENT_DISK_SPACE);

} else {

  var fChrome     = getFolder("Chrome");
  var fComponents = getFolder("Components");
  var fDefaults   = getFolder("Program", "defaults/pref");

  // workaround for Mozilla 1.8a3 and newer, failing to register enigmime correctly

  var delComps = [ "compreg.dat" ]; // Components registry

  for (var j=0; j<delComps.length; j++) {
     var delFile = getFolder(fComponents, delComps[j]);
     if (File.exists(delFile))
        File.remove(delFile);
  }

  switch (getPlatform()) {
  case APP_PLATFORM_LINUX:
    addDirectory("", "platform/"+ABI_PLATFORM_LINUX+"/components",    fComponents, "");
    break;
  case APP_PLATFORM_WIN:
    addDirectory("", "platform/"+ABI_PLATFORM_WIN+"/components",    fComponents, "");
    break;
  case APP_PLATFORM_MAC:
    addDirectory("", "platform/"+ABI_PLATFORM_DARWIN_PPC+"/components",    fComponents, "");
    addDirectory("", "platform/"+ABI_PLATFORM_DARWIN_X86+"/components",    fComponents, "");
    break;
  }

  err = getLastError();
  if (err == DOES_NOT_EXIST) {
    // error code: file does not exist
    logComment("platform dependent directory does not exist: " + err);
    resetError();
  }
  else if (err != SUCCESS) {
    cancelInstall(err);
  }

  // addDirectory: blank, archive_dir, install_dir, install_subdir
  addDirectory("", "components",    fComponents, "");
  addDirectory("", "chrome",        fChrome,     "");
  addDirectory("", "defaults/pref", fDefaults,   "");


  err = getLastError();
  if (err == ACCESS_DENIED) {
    alert("Unable to write to components directory "+fComponents+".\n You will need to restart the browser with administrator/root privileges to install this software. After installing as root (or administrator), you will need to restart the browser one more time, as a privileged user, to register the installed software.\n After the second restart, you can go back to running the browser without privileges!");

    cancelInstall(ACCESS_DENIED);

  } else if (err != SUCCESS) {
    cancelInstall(err);

  } else {
    // Register chrome

    var isTbird = false;

    registerChrome(PACKAGE | DELAYED_CHROME, getFolder("Chrome","enigmail.jar"), "content/enigmail/");

    if (! isTbird) {
      registerChrome(   SKIN | DELAYED_CHROME, getFolder("Chrome","enigmail-skin.jar"), "skin/modern/enigmail/");

      registerChrome(   SKIN | DELAYED_CHROME, getFolder("Chrome","enigmail-skin.jar"), "skin/classic/enigmail/");
    }
    else {
      registerChrome(   SKIN | DELAYED_CHROME, getFolder("Chrome","enigmail-skin-tbird.jar"), "skin/classic/enigmail/");
    }
    registerChrome( LOCALE | DELAYED_CHROME, getFolder("Chrome","enigmail.jar"), "locale/en-US/enigmail/");
EOT

# Prepare languages other than en-US

if [ -s ${srcDir}/lang/current-languages.txt ]; then
  localeJar=chrome/${xpiModule}-locale.jar

  echo '      <Description about="urn:mozilla:extension:file:enigmail-locale.jar">' > ${targetDir}/install.rdf.t2

  for lang in `cat ${srcDir}/lang/current-languages.txt`; do
    echo '        <em:locale>locale/'$lang'/enigmail/</em:locale>' >> ${targetDir}/install.rdf.t2
    echo 'locale        enigmail    '$lang'       jar:chrome/enigmail-locale.jar!/locale/'$lang'/enigmail/' >> ${targetDir}/chrome.manifest
    echo '    registerChrome( LOCALE | DELAYED_CHROME, getFolder("Chrome","enigmail-locale.jar"), "locale/'$lang'/enigmail/");' >> ${targetDir}/install.js
  done
  echo '      </Description>' >> ${targetDir}/install.rdf.t2

  awk -v langFile=${targetDir}/install.rdf.t2 '
    BEGIN {
      lines=0
      while (getline < langFile) {
        lineTxt[++lines] = $0
      }
    }
    /<!-- localeFile placeholder -->/ {
      for (i=0; i<lines; i++) {
        print lineTxt[i+1]
      }
      next;
    }
    {
      print $0
    }' ${targetDir}/install.rdf.t1 >${targetDir}/install.rdf
    rm ${targetDir}/install.rdf.t1 ${targetDir}/install.rdf.t2
else
  localeJar=""
  mv ${targetDir}/install.rdf.t1 ${targetDir}/install.rdf
fi


# finalize install.js
cat <<EOT >> ${targetDir}/install.js
    err = getLastError();

    if (err != SUCCESS) {
      cancelInstall(err);

    } else {
      performInstall();
    }
  }
}
EOT

cd ${srcDir}/package

enigmimeDll=${libPrefix}enigmime${dllSuffix}
dllFile=platform/${platform}/components/${enigmimeDll}

cd "$targetDir"


mkdir -p platform/${platform}/components
cp components/${enigmimeDll} ${dllFile}


zip ${xpiFile} \
    components/${xpiModule}.xpt \
    components/${xpiModule}.js \
    components/enigprefs-service.js \
    defaults/preferences/enigmail.js \
    defaults/pref/enigmail.js \
    chrome/${xpiModule}.jar \
    chrome/${xpiModule}-skin.jar \
    chrome/${xpiModule}-skin-tbird.jar \
    ${localeJar} \
    components/ipc.xpt \
    components/enigmime.xpt \
    ${dllFile} \
    chrome.manifest \
    install.js \
    install.rdf

rm install.rdf chrome.manifest install.js
