#!/bin/sh
###########################################################################
#
# Execute this script in the top-level Postfix source directory.
# This script has been tested with Postfix version 2.7.0 and 2.8.0.
#
# NOTE: This script might not work correctly with earlier Postfix versions.
#
# This script was originally written by Victor Didovicher and kept updated by
# Ihsan Dogan.
#
# For more information, visit http://ihsan.dogan.ch/postfix/
#
# Script version 0.4.0
# (c) Victor Didovicher <vkd79@yahoo.com>
# (c) Mark Phillips - 360is.com
# (c) CND AG, Switzerland, http://www.cnd-ag.ch/
# (c) Ihsan Dogan <ihsan@dogan.ch>
#
###########################################################################
#
# ChangeLog:
# * 27.07.2011 v0.4.0 (Ihsan Dogan)
#   - For smaller packages, the package is converted to a class archive
#     package. Based on Markus Mayer's pkgzip and Garry Zacheiss' packaging
#     scripts.
#
# * 07.03.2011 v0.3.6 (Ihsan Dogan)
#   - Version info in pkginfo is now compliant with pkgutil.
#     Bug report from Rudy Gevaert.
#
# * 16.09.2010 v0.3.5 (Ihsan Dogan)
#   - Removed /opt/csw from path variable
#   - Added /usr/sfw to the path variable
#   - Preremove scripts waits till Postfix has been really stopped
#
# * 18.02.2010 v0.3.4 (Ihsan Dogan)
#   - Added Symlink /usr/sbin/sendmail -> /usr/lib/sendmail
#
# * 16.05.2009 v0.3.3 (Ihsan Dogan)
#   - fixed the SUNWman hack for Postfix 2.6.0
#   - Since 2.6.0 post-install, postfix-files and postfix-script are located in
#     /usr/libexec/postfix, so there is no need to copy these files with the
#     postinstall script.
#   - Tested with Postfix 2.6.0
#
# * 22.04.2009 v0.3.2 (Ihsan Dogan)
#   - fixed chroot execution in postinstall and preinstall scripts
#     (Bug report from Niklas Edmundsson)
#   - Set permission for all directories in /var/spool/postfix
#   - Added script version to pkginfo.
#
# * 19.04.2009 v0.3.1 (Ihsan Dogan)
#   - fixed several directory permissions (prototype)
#   - setting uid and gid for the postfix user and postdrop group to 26
#   - fixed postinstall script (check if group exists)
#   - commands in preinstall, postinstall and preremove are executed now in
#     a chroot. (Bug report from Niklas Edmundsson)
#
# * 11.09.2008 v0.3.1pre (Ihsan Dogan)
#   - fixed permission for /var/lib (prototype)
#
# * 18.07.2008 v0.3.1pre (Ihsan Dogan)
#   - postinstall creates now a /etc/mail/aliases file if it doesn't exist
#   - postinstall executes now newaliases
#
# * 02.01.2008 v0.3 (Ihsan Dogan)
#   - Added a preremove script to unregister the Postfix SMF manifest during
#     the package uninstallation
#   - Postfix is disabled in the preremove script before the uninstallation
#   - removed all SysV init stuff
#   - postinstall script is now quiet (no message about checking permissions)
#   - we verify now if $src_dir/$packageName exists, before executing rm
#   - added a message how to start Postfix with SMF to the postinstall script
#   - Changed directions to fit in one line
#
# * 28.12.2007 v0.3pre (Ihsan Dogan)
#   - Changed paths in the smf manifest from /opt/csw to /usr
#   - Changed smf_dir to /var/svc/manifest
#   - added variable smf_category and set it to 'network'
#
# * 26.11.2007 v0.3pre (Mark Phillips)
#   - Solaris 10 only version - SMF manifest added
#   - postconf -dh instead of sed business
#   - added OS version to $pkgFileName
#
# * 22.10.2007 v0.2.4 (Ihsan Dogan)
#   - Fixed VERSION in pkginfo
#
# * 08.05.2007 v0.2.3 (Ihsan Dogan)
#   - Postinstall is now copying post* files allways to /etc/postfix
#   - Fixed the SUNWman hack: removed entry for the mailq manpage in
#     postfix-files
#
# * 07.05.2007 v0.2.2 (Ihsan Dogan)
#   - Changed manpage directory to /usr/share/man
#   - Added a revision number to pkginfo and to the filename
#
# * 06.05.2007 v0.2.1 (Ihsan Dogan)
#   - Tested with Postfix 2.4.1
#   - The required postfix user and postdrop group are now added by the
#     postinstall script
#   - Fixed init script
#   - Added HOTLINE and VENDOR to the pkginfo
#   - Added the architecture to the package filename
#   - Added package incompatibility to SUNWsndmr and SUNWsndmu
#
# * 10.04.2007 v0.2 (Ihsan Dogan)
#   - Added dependencies for SUNW and CSW packages
#   - config files are not anymore part of the package and are copied by
#     the postinstall script
#
# * 28.02.2007 v0.1.7 (Ihsan Dogan)
#   - Made it work with Postfix 2.3.x
#   - changed PATH variable to use /opt/csw instead of /usr/local
#
# * 28/02/2002 v0.1.6
#   - Fixed permissions for some of the /usr/* dirs
#
###########################################################################
#
# Please contact me at ihsan@dogan.ch for bug reports and questions.
#
###########################################################################

# ------------------------------------------------------------------------
# User Configurable Area
# ------------------------------------------------------------------------

# if possible, please don't change this values
mail_owner=postfix
setgid_group=postdrop

# ------------------------------------------------------------------------
# No editing should be needed below this line
# ------------------------------------------------------------------------

scriptversion=0.4.0
PATH=/usr/bin:/usr/sbin:/usr/ccs/bin:/usr/sfw/bin:/usr/sfw/sbin

###########################################################################
# Create Build directory and package directory
###########################################################################
echo " ----------------- PREPARING TEMP FILES ----------------- "
packageName=CNDpostfix
pkgVersion=`./bin/postconf -dh mail_version`
pkgRevision=`date '+%yy%mm%dd' | sed s/y// | sed s/m// | sed s/d//`
pkgFileName=$packageName-$pkgVersion\,REV\=$pkgRevision-`uname -s``uname -r`-`uname -p`
src_dir=`/bin/pwd`
bld_dir=$src_dir/$packageName/build
pkg_dir=$src_dir/$packageName/package
distconf_dir=$src_dir/$packageName/build/etc/postfix/distconf
conf_dir=$src_dir/$packageName/build/etc/postfix
smf_dir=$bld_dir/var/svc/manifest
smf_category=network

if [ -x `which pbzip2` ]; then
	bzip2=`which pbzip2`
else
	bzip2=`which bzip2`
fi

if [ -d $src_dir/$packageName ]; then
	rm -rf $src_dir/$packageName
fi

mkdir -p $bld_dir $pkg_dir $smf_dir/$smf_category

###########################################################################
# Copy Postfix Files
###########################################################################
make non-interactive-package install_root=$bld_dir manpage_directory=/usr/share/man

# -------------------------------------------------------------------------
# dirty hack to fix a conflict with SUNWman
# -------------------------------------------------------------------------
rm $bld_dir/usr/share/man/man1/mailq.1
grep -v '$manpage_directory/man1/mailq.1:f:root:-:644' $bld_dir/usr/libexec/postfix/postfix-files > /tmp/postfix-files.tmp
mv /tmp/postfix-files.tmp $bld_dir/usr/libexec/postfix/postfix-files

# -------------------------------------------------------------------------
# Create a symlink for sendmail in /usr/sbin
# -------------------------------------------------------------------------
ln -s ../lib/sendmail $bld_dir/usr/sbin/sendmail

# -------------------------------------------------------------------------
# move config files to etc/postfix/distconf and install them with the
# postinstall script to avoid that the files will be overwritten during an
# upgrade
# -------------------------------------------------------------------------
mkdir $distconf_dir
mv `find $conf_dir -type f` $distconf_dir

###########################################################################
# Create smf manifest
###########################################################################
cat > $smf_dir/$smf_category/postfix.xml << __EOF__
<?xml version="1.0"?>
<!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">

<!-- PostFix Manifest for TSISpostfix: Mark Phillips - 360is.com -->
<!-- Based on original by Ben Rockwood - cuddletech.com -->

<service_bundle type='manifest' name='postfix'>

<service
       name='network/postfix'
       type='service'
       version='1'>

        <create_default_instance enabled='false'/>
        <single_instance/>

        <dependency name='config-file'
                    grouping='require_all'
                    restart_on='none'
                    type='path'>
                <service_fmri value='file:///etc/postfix/main.cf'/>
        </dependency>

       <dependency name='loopback'
                   grouping='require_all'
                   restart_on='error'
                   type='service'>
               <service_fmri value='svc:/network/loopback:default'/>
       </dependency>

       <dependency name='physical'
                   grouping='require_all'
                   restart_on='error'
                   type='service'>
               <service_fmri value='svc:/network/physical:default'/>
       </dependency>

       <dependency name='fs-local'
                   grouping='require_all'
                   restart_on='none'
                   type='service'>
               <service_fmri value='svc:/system/filesystem/local'/>
       </dependency>

       <exec_method
               type='method'
               name='start'
               exec='/usr/sbin/postfix start'
               timeout_seconds='60' />

       <exec_method
               type='method'
               name='stop'
               exec='/usr/sbin/postfix stop'
               timeout_seconds='60' />

       <exec_method
               type='method'
               name='refresh'
               exec='/usr/sbin/postfix reload'
               timeout_seconds='60' />

       <stability value='Unstable' />

       <template>
               <common_name>
                       <loctext xml:lang='C'>Postfix SMTP Server</loctext>
               </common_name>
               <documentation>
                       <manpage title='postfix' section='1' />
                       <doc_link name='postfix.org'
                               uri='http://www.postfix.org/documentation.html' />
               </documentation>
       </template>
</service>

</service_bundle>
__EOF__

###########################################################################
# Strip Binary executable files (little addition from Viktor Duchovni)
# GNU strip seemed to do freaky things. I force to SUN's strip here.
###########################################################################
find $bld_dir -type f | xargs file |
    awk -F: '/not stripped/{print $1}' | xargs /usr/ccs/bin/strip

###########################################################################
############## CREATING SOLARIS PACKAGE FROM BUILD DIRECTORY ##############
###########################################################################
echo " ------------------- BUILDING PACKAGE ------------------- "

# -------------------------------------------------------------------------
# Create package prototype file
# -------------------------------------------------------------------------
(
    cd $bld_dir

    # Get rid of first / since pkgproto does not show it
    cmd_dir=`echo $command_directory | sed -e 's;^/;;'`
    #que_dir=`echo $queue_directory | sed -e 's;^/;;'`

    find . ! -name prototype | sort | pkgproto | nawk '
            { $5="root"; $6="other"; }
            $3 ~  /^usr$/                            {              $6="sys"; }
            $3 ~  /^usr\/bin/                        {              $6="bin"; }
            $3 ~  /^usr\/lib/                        {              $6="bin"; }
            $3 ~  /^usr\/sbin/                       {              $6="bin"; }
            $3 ~  /^usr\/share/                      {              $6="sys"; }
            $3 ~  /^usr\/share\/man/                 {              $6="bin"; }
            $3 ~  /^etc/                             {              $6="sys"; }
            $3 ~  /^var/                             {              $6="sys"; }
            $3 ~  /^var\/lib/                        {              $6="other"; }
            $3 ~  /^var\/lib\/postfix/               { $5="postfix"; $6="other"; }
            $3 ~  /^var\/spool\/postfix\/active/     { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/bounce/     { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/corrupt/    { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/defer/      { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/deferred/   { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/flush/      { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/hold/       { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/incoming/   { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/private/    { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/saved/      { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/trace/      { $5="postfix"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/pid/        { $5="root"; $6="sys"; }
            $3 ~  /^var\/spool\/postfix\/maildrop/   { $5="postfix"; $6="postdrop"; }
            $3 ~  /^var\/spool\/postfix\/postdrop/   { $5="postfix"; $6="postdrop"; }
            $3 ~  /^var\/spool\/postfix\/public/     { $5="postfix"; $6="postdrop"; }
            $3 == "var/spool"                        {              $6="bin"; }
            $3 == "opt"                              { $4="0775";   $6="sys"; }

            # Set proper group for command executables
            # Postinstall should correct these but
            # forcing group ownership here is just a safeguard

            $3 ~  "'"$cmd_dir"'/postdrop$"  { $4="2755"; $6=PGROUP; }
            $3 ~  "'"$cmd_dir"'/postqueue$" { $4="2755"; $6=PGROUP; }

            { print; }
            END { print "i pkginfo=info"; print "i postinstall=postinstall"; print "i preinstall=preinstall";  print "i preremove=preremove"; print "i depend=depend"; }
    ' POWNER=$mail_owner PGROUP=$setgid_group > prototype
)

# -------------------------------------------------------------------------
# Create package info file
# -------------------------------------------------------------------------
# add additional parameters to the pkginfo file
#    PKG_SRC_NOVERIFY: don't check for files in reloc and root directory
#    PKG_DST_QKVERIFY: quick verify: fix instead of check of file attribs
#    PKG_CAS_PASSRELATIVE: instead of <src> <dst> pair lines, first
#                          pass $SUNW_PKG_DIR and then <dst> lines to cas
cat > $bld_dir/info << __EOF__
PKG=$packageName
NAME=Postfix MTA
CATEGORY=application
CLASSES=none
ARCH=`uname -p`
VERSION=${pkgVersion}r${scriptversion},REV=${pkgRevision}
PSTAMP=`./bin/postconf -d | grep mail_release_date | sed -e 's/[a-zA-Z_]* = \([0-9.]*\)/postfix\1/g'`
BASEDIR=/
VENDOR=http://www.postfix.org/ packaged by Ihsan Dogan
HOTLINE=ihsan@dogan.ch
PKG_SRC_NOVERIFY=none
PKG_DST_QKVERIFY=none
PKG_CAS_PASSRELATIVE=none
__EOF__

# -------------------------------------------------------------------------
# Create depend file
# -------------------------------------------------------------------------
cat > $bld_dir/depend << __EOF__
P SUNWcsl
P SUNWcslr
P SUNWlibmsr
P SUNWopenssl-libraries
P SUNWlibsasl
P SUNWpr
P SUNWtls
I SUNWsndmr
I SUNWsndmu
__EOF__

# -------------------------------------------------------------------------
# Create preinstall script to create users
# -------------------------------------------------------------------------
cat > $bld_dir/preinstall << __EOF__
#!/bin/sh
# check, if the postdrop group does exist
grep '^postdrop:' \$PKG_ROOT_DIR/etc/group >/dev/null
if [ \$? -ne 0 ] ; then
        \$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/bin/getent group $setgid_group >/dev/null
        if [ \$? -ne 0 ] ; then
                NEEDGROUP=1
        fi
fi
# check, if the postfix user does exist
grep '^$mail_owner:' \$PKG_ROOT_DIR/etc/passwd >/dev/null
if [ \$? -ne 0 ] ; then
        \$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/bin/getent passwd $mail_owner >/dev/null
        if [ \$? -ne 0 ] ; then
                NEEDUSER=1
        fi
fi
# create the postdrop group, if NEEDGROUP=1
if [ "\$NEEDGROUP" = 1 ] ; then
        echo Adding required $setgid_group group
        \$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/sbin/groupadd  -g 26 $setgid_group
fi
# create the postfix user, if NEEDUSER=1
if [ "\$NEEDUSER" = 1 ] ; then
        echo Adding required $mail_owner user
        # create the $mail_owner user
        \$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/sbin/useradd -u 26 -d / -c 'Postfix pseudo-user' -s /bin/false $mail_owner
fi
__EOF__

# -------------------------------------------------------------------------
# Create postinstall script to fix permissions / check queue dir,
# copy config files and register the SMF manifest
# -------------------------------------------------------------------------
cat > $bld_dir/postinstall << __EOF__
#!/bin/sh
cd \$BASEDIR/etc/postfix/distconf/
for i in * ; do
        if [ ! -f \$BASEDIR/etc/postfix/\$i ]; then
                cp -p \$i \$BASEDIR/etc/postfix
        fi
done
\$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/sbin/postfix set-permissions upgrade-configuration \
 setgid_group=$setgid_group mail_owner=$mail_owner
\$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/sbin/svccfg import /var/svc/manifest/network/postfix.xml
if [ ! -f \$BASEDIR/etc/mail/aliases ]; then
cat > \$BASEDIR/etc/mail/aliases << _EOF_
postmaster:	root
MAILER-DAEMON:	postmaster
bin:		root
daemon:		root
system:		root
toor:		root
uucp:		root
manager:	root
dumper:		root
operator:	root
decode:		root
nobody:		/dev/null
_EOF_
fi
\$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/bin/newaliases
echo
echo To start Postfix, execute \'svcadm enable svc:/network/postfix:default\'
__EOF__

# -------------------------------------------------------------------------
# Create preremove script to unregister the SMF manifest
# -------------------------------------------------------------------------
cat > $bld_dir/preremove << __EOF__
#!/bin/sh
\$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/sbin/svcadm disable -s svc:/network/postfix:default
\$BASEDIR/usr/sbin/chroot \$BASEDIR /usr/sbin/svccfg delete svc:/network/postfix:default
__EOF__

# -------------------------------------------------------------------------
# Create the package
# -------------------------------------------------------------------------
pkgmk -d $pkg_dir -f $bld_dir/prototype -r $bld_dir -o

# -------------------------------------------------------------------------
# Convert to class archive package
# -------------------------------------------------------------------------
# cpio the package and compress it with bzip2
mkdir -p $src_dir/$packageName/package/$packageName/archive
if [ -f /tmp/$packageName.filelist ]; then
  rm /tmp/$packageName.filelist
fi
awk '(($2 == "f" || $2 == "v" || $2 == "e") && $3 == "none") { print $4; }' \
  $src_dir/$packageName/package/$packageName/pkgmap > /tmp/$packageName.filelist
(cd $src_dir/$packageName/package/$packageName/reloc && cpio -oc -C 512 < /tmp/$packageName.filelist) | \
  $bzip2 -c -9 > $src_dir/$packageName/package/$packageName/archive/none.cpio.bz2 || exit 1
rm -rf $src_dir/$packageName/package/$packageName/reloc

# Create the installation class action script
cat > $src_dir/$packageName/package/$packageName/install/i.none << __EOF__
if read pkgdir
then	cd "\${BASEDIR:-/}" && cat >\$PKGSAV/filelist &&
	bzcat "\$pkgdir/archive/\`expr "//\$0" : '.*/i\.\(.*\)'\`.cpio.bz2" | 
	cpio -idmukv -C 512 -E "\$PKGSAV/filelist" && rm -f "\$PKGSAV/filelist"
fi >&2 || exit 2
__EOF__

# -------------------------------------------------------------------------
# Convert to package stream
# -------------------------------------------------------------------------
echo | pkgtrans -os $pkg_dir $src_dir/$pkgFileName.pkg >/dev/null 2>&1

###########################################################################
######################### DONE: Show Directions ###########################
###########################################################################

echo
echo ".:: makePostfixPkg.sh Version $scriptversion ::."
echo
echo "+-----------------------------------------------------------------------"
echo "| Package File: $pkgFileName.pkg"
echo "| To Install: pkgadd -d $pkgFileName.pkg"
echo "+-----------------------------------------------------------------------"
echo
echo "(c) Ihsan Dogan <ihsan@dogan.ch> (current maintainer)"
echo "(c) CND AG, Switzerland, http://www.cnd-ag.ch/"
echo "(c) Victor Didovicher <vkd79@yahoo.com> (initial script)"
echo "(c) Mark Phillips - 360is.com (SMF integration)"
echo

###########################################################################
# Clean up used tmp dirs
###########################################################################
/bin/rm -rf $src_dir/$packageName
/bin/rm -f /tmp/$packageName.filelist

exit 0
