#!/bin/sh
##
##  OpenPKG Binary Bootstrap Package (self-extracting shell script)
##  Copyright (c) 2000-2005 OpenPKG Foundation e.V. <http://openpkg.net/>
##  Copyright (c) 2000-2005 Ralf S. Engelschall <http://engelschall.com/>
##
##  Permission to use, copy, modify, and distribute this software for
##  any purpose with or without fee is hereby granted, provided that
##  the above copyright notice and this permission notice appear in all
##  copies.
##
##  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
##  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
##  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
##  IN NO EVENT SHALL THE AUTHORS AND COPYRIGHT HOLDERS AND THEIR
##  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
##  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
##  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
##  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
##  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
##  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
##  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
##  SUCH DAMAGE.
##

#   configuration
l_me="$0"
o_help=no
o_version=no
o_tar=no
l_prefix='@l_prefix@'
l_musr='@MUSR@'
l_mgrp='@MGRP@'
l_platform="@l_platform@"
l_release="@l_release@"
l_version="@l_version@"

#   establish standard environment
PATH="$PATH:/bin:/sbin:/usr/bin:/usr/sbin"
LC_CTYPE=C
export LC_CTYPE
umask 022

#   parse command line options
for opt
do
    case $opt in
        -*=*) arg=`echo "$opt" | sed 's/^[-_a-zA-Z0-9]*=//'` ;;
           *) arg='' ;;
    esac
    case $opt in
        -h | --help    ) o_help=yes     ;;
        -v | --version ) o_version=yes  ;;
        -t | --tar     ) o_tar=yes      ;;
        --prefix=*     ) l_prefix=$arg  ;;
        *              ) o_help=yes     ;;
    esac
done
if [ ".$o_version" = .no -a ".$l_prefix" = . ]; then
    o_help=yes
fi
if [ ".$o_help" = .yes ]; then
    echo "Usage: sh $l_me" 2>&1
    echo "       [--prefix=<prefix>] [-t|--tar]" 2>&1
    echo "       [-h|--help] [-v|--version]" 2>&1
    exit 1
fi

#   make sure all essential installation tools are available
for tool in sed mkdir dd tar chown chgrp; do
    found=no
    case $tool in
        /* )
            if [ -f $tool ]; then
                found=yes
            fi
            ;;
        * )
            for p in `IFS=:; echo $PATH`; do
                if [ -f "$p/$tool" ]; then
                    found=yes
                    break
                fi
            done
            ;;
    esac
    if [ ".$found" = .no ]; then
        echo "$l_me:ERROR: unable to find installation tool \"$tool\"" 1>&2
        exit 1
    fi
done

#   optionally extract the embedded tarball only
if [ ".$o_tar" = .yes ]; then
    tmpdir="${TMPDIR-/tmp}/openpkg.$$"
    ( umask 077 && mkdir $tmpdir) || exit 1
    dd if=$l_me bs=8192 skip=8 2>/dev/null |\
    ( cd $tmpdir || exit 1
      tar xf - 2>/dev/null || exit 1
      ./openpkg.bzip2 -d -c openpkg.tar.bz2
    ) || exit 1
    rm -rf $tmpdir
    exit 0
fi

#   display version and copyright header
echo "OpenPKG ${l_release} Binary Bootstrap Package, version ${l_version}"
echo "Built for prefix ${l_prefix} on target platform ${l_platform}"
if [ ".$o_version" = .yes ]; then
    exit 0
fi

#   determine current username
cusr=`(id -un) 2>/dev/null ||\
      (id | sed -e 's;^[^(]*(\([^)]*\)).*;\1;') 2>/dev/null ||\
      (whoami) 2>/dev/null ||\
      (who am i | cut "-d " -f1) 2>/dev/null ||\
      echo ${LOGNAME-"NN"}`

#   running the embedded %pre script for hooking into the system environment
echo "++ hooking OpenPKG instance into system environment"
prefix="$l_prefix"
susr='@SUSR@'; sgrp='@SGRP@'
musr='@MUSR@'; mgrp='@MGRP@'
rusr='@RUSR@'; rgrp='@RGRP@'
nusr='@NUSR@'; ngrp='@NGRP@'
suid='@SUID@'; sgid='@SGID@'
muid='@MUID@'; mgid='@MGID@'
ruid='@RUID@'; rgid='@RGID@'
nuid='@NUID@'; ngid='@NGID@'
set -- 1 # emulate RPM's $1 when executing scripts
#   ---- BEGIN EMBEDDED %pre SCRIPT ----
@PRE@
#   ---- END EMBEDDED %pre SCRIPT ----

#   make sure prefix/root directory exists
#   and has correct permissions and owner/group
if [ ! -d $l_prefix ]; then
    #   create prefix/root directory from scratch
    echo "++ creating OpenPKG instance root directory \"$l_prefix\""
    d=''
    for c in `IFS=/; echo $l_prefix`; do
        d="$d/$c"
        if [ ! -d $d ]; then
            mkdir $d || exit 1
            chmod 755 $d || exit 1
            if [ ".$cusr" = .root ]; then
                chown $musr $d >/dev/null 2>&1 || true
                chgrp $mgrp $d >/dev/null 2>&1 || true
            fi
        fi
    done
else
    #   adjust already existing prefix/root directory
    echo "++ fixating OpenPKG instance root directory \"$l_prefix\""
    ( cd $l_prefix || exit 1
      chmod 755 . || exit 1
      if [ ".$cusr" = .root ]; then
          chown $musr . >/dev/null 2>&1 || true
          chgrp $mgrp . >/dev/null 2>&1 || true
      fi
    ) || exit 1
fi

#   extract and install binary distribution files
echo "++ extracting OpenPKG binary distribution"
dd if=$l_me bs=8192 skip=8 2>/dev/null |\
    (cd $l_prefix; tar xf - 2>/dev/null)
echo "++ installing OpenPKG binary distribution"
( cd $l_prefix || exit 1
  ./openpkg.bzip2 -d -c openpkg.tar.bz2 | ./openpkg.tar xf - 2>/dev/null
  rm -f openpkg.tar openpkg.bzip2 openpkg.tar.bz2 >/dev/null 2>&1 || true
) || exit 1

#   fixate installation files
echo "++ fixating OpenPKG instance filesystem hierarchy"
( echo 'fixate () {'
  echo '    chmod "$1" "$4"'
  echo '    chown "$2" "$4"'
  echo '    chgrp "$3" "$4"'
  echo '}'
  $l_prefix/bin/openpkg rpm -qa \
      --qf '[fixate %7.7{FILEMODES:octal} %{FILEUSERNAME:shescape} %{FILEGROUPNAME:shescape} ::%{FILENAMES:shescape}\n]' |\
      grep -v '(none)' | sed 's/^fixate .../fixate /' | sed -e "s; ::\\(.\\)@l_prefix@; \\1$l_prefix;"
) | sh 2>/dev/null || true

#   running the embedded %post script
echo "++ post-processing OpenPKG bootstrap installation"
prefix="$l_prefix"
susr='@SUSR@'; sgrp='@SGRP@'
musr='@MUSR@'; mgrp='@MGRP@'
rusr='@RUSR@'; rgrp='@RGRP@'
nusr='@NUSR@'; ngrp='@NGRP@'
suid='@SUID@'; sgid='@SGID@'
muid='@MUID@'; mgid='@MGID@'
ruid='@RUID@'; rgid='@RGID@'
nuid='@NUID@'; ngid='@NGID@'
set -- 1 # emulate RPM's $1 when executing scripts
#   ---- BEGIN EMBEDDED %post SCRIPT ----
@POST@
#   ---- END EMBEDDED %post SCRIPT ----

#   display final information
( echo "Congratulations!"
  echo ""
  echo "You have successfully installed an OpenPKG ${l_release} instance"
  echo "under prefix ${l_prefix} on target platform ${l_platform}."
  echo ""
  echo "For details about this OpenPKG instance, run any of the"
  echo "following typical OpenPKG RPM query commands:"
  echo ""
  echo "    \$ ${l_prefix}/bin/openpkg rpm -qa"
  echo "    \$ ${l_prefix}/bin/openpkg rpm -qi  openpkg"
  echo "    \$ ${l_prefix}/bin/openpkg rpm -qlv openpkg"
  echo ""
  echo "To check the integrity of the entire OpenPKG instance,"
  echo "run the following OpenPKG RPM verify command:"
  echo ""
  echo "    \$ ${l_prefix}/bin/openpkg rpm -Va"
  echo ""
  echo "To install software packages into this OpenPKG instance, run"
  echo "the following two OpenPKG RPM build commands for each package:"
  echo ""
  echo "    \$ ${l_prefix}/bin/openpkg rpm --rebuild /path/to/foo-*.src.rpm"
  echo "    \$ ${l_prefix}/bin/openpkg rpm -Uvh ${l_prefix}/RPM/PKG/foo-*.rpm"
  echo ""
  echo "To remove a software package later, just run:"
  echo ""
  echo "    \$ ${l_prefix}/bin/openpkg rpm -e foo"
  echo ""
  echo "To remove the whole OpenPKG instance under prefix ${l_prefix},"
  echo "just remove every package as shown above. As you finally"
  echo "remove the package \"openpkg\", the OpenPKG instance itself"
  echo "will be unlinked from the system and removed as well."
  echo ""
  echo "Thank you for flying OpenPKG..."
  echo "                                        Ralf S. Engelschall"
  echo "                                        The OpenPKG Project"
  echo "                                        openpkg@openpkg.org"
) | $l_prefix/lib/openpkg/rpmtool msg -b -t info

#   die explicitly just before the shell would discover
#   that we carry mega-bytes of data with us... ;-)
exit 0

#   the distribution tarball is appended in raw format directly to the
#   end of this script, just leaded by padding whitespaces which make
#   sure that the tarball data starts at the pre-defined offset of 64KB.
#   This allows us to unpack the tarball by just skipping the leading
#   64KB (= 8192*8, see above).

