#!/bin/sh
#
# $Id: balou-install-theme 4648 2004-08-24 12:39:59Z benny $
#
# Copyright (c) 2004 Benedikt Meurer <benny@xfce.org>
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#                                                                              
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#                                                                              
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#

leave()
{
  if test -d "${tmpdir}"; then
    rm -rf "${tmpdir}" >/dev/null 2>&1
  fi
  exit $1
}

if test $# -ne 2; then
  echo "Usage: balou-install-theme <theme> <targetdir>" >&2
  exit 1
fi

tmpdir=""
themedir="${1}"
targetdir="${2}"

# ensure the target directory exists
if test ! -d "${targetdir}"; then
  mkdirhier "${targetdir}" >/dev/null 2>&1
  if test $? -ne 0; then
    echo "Unable to create themes directory ${targetdir}." >&2
    exit 1
  fi
fi

# if the source is a file, we expect it to be a tarball
if test -f "${themedir}"; then
  tmpdir=`mktemp -d "/tmp/balou-theme-XXXXXX"` || exit 1

  if echo "${themedir}" | grep '\.tar\.gz$' >/dev/null 2>&1; then
    tar xzf "${themedir}" -C "${tmpdir}" >/dev/null 2>&1
    if test $? -ne 0; then
      echo "Unable to extract theme." 2>&2
      leave 1
    fi
  else
    echo "Not a splash theme file: ${themedir}." >&2
    leave 1
  fi

  themerc=`ls ${tmpdir}/*/balou/themerc` || leave 1
  baloudir=`dirname "${themerc}"` || leave 1
  topdir=`dirname "${baloudir}"` || leave 1

  if test ! -d "${topdir}" -o ! -d "${topdir}/balou/"; then
    echo "Invalid theme file format." >&2
    leave 1
  fi

  themedir="${topdir}"
fi

# verify the theme content
if test -d "${themedir}"; then
  if test ! -d "${themedir}/balou/"; then
    echo "No balou sub directory in theme." >&2
    leave 1
  fi

  if test ! -r "${themedir}/balou/themerc"; then
    echo "No themerc file in theme." >&2
    leave 1
  fi
fi

# install the theme
themebase=`dirname "${themedir}"`
themename=`basename "${themedir}"`
(cd "${themebase}" \
   && tar cf - "${themename}/balou/" \
    | (cd "${targetdir}" && tar xf -)) >/dev/null 2>&1
if test $? -ne 0; then
  echo "Unable to install the theme ${themename} from ${themebase} to ${targetdir}." >&2
  leave 1
fi

# tell the caller the name of the installed plugin
echo "${themename}"
leave 0
