#!/bin/bash

# Slackware build script for SystemGraph
# http://www.decagon.de/sw/systemgraph/

# Copyright 2008  Leonardo Roman (leoroman@gmail.com)
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS 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 AUTHOR 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.

# Retorna el nombre del archivo sin la extecion de empaquetado:
# .tar.gz, .tgz , .bz2 ...
get_basename() {
# $1 Archivo comprimido del cual se quiere eliminar la extencion
	BASE=$(basename $1 .tgz)
	[[ "$BASE" != "$1" ]] || BASE=$(basename $1 .tar.gz)
	[[ "$BASE" != "$1" ]] || BASE=$(basename $1 .tar.bz2)
	echo $BASE
}

# $1 DIR donde se encuentra la instalacion a emaquetar
# $2 Nombre del Paquete a crear
# $3 Destino donde MOVER el paquete creado
create_package() {
	echo "Creando el paquete $2 ..." 1>&2
	cd $1 || \  # && \  Por ahora el sig bloque se omite...
{
	find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : \
		| xargs strip --strip-unneeded 2> /dev/null || true
	find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : \
		| xargs strip --strip-unneeded 2> /dev/null || true
} && \
# Compress the man page(s):
	find usr/man -type f -name "*.?" -exec gzip -9f '{}' \; &> /dev/null
	makepkg --linkadd y --chown n $3/$2 &>/dev/null \
	    || echo "Error empaquetando: $2" 1>&2 # && exit 1
#md5sum $PRGNAM-$VERSION-$ARCH-$BUILD.tgz > $PRGNAM-$VERSION-$ARCH-$BUILD.tgz.md5
#cat $PKG/install/slack-desc | grep "^${PRGNAM}" > $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.txt
	echo "Eliminando directorio de instalacion temporal: $1"
	cd - 1>/dev/null
	rm -rf $1
}

# Analiza el string $1 separandolo por '-' y retorna todo
# lo anterior a la primer porcion que es un numero +
# la primer porcion que ES un numero.
# es decir: nombre-packete-1.0
get_package_name() {
	IFS+='-' ; PN='' PV=''
	for I in $1 ; do
	   if [ ! $PV ]; then
		echo $I | grep ^[[:digit:]] >/dev/null && PV=$I && continue #|| echo $I
		(( ${#PN} != 0 )) && PN=$PN'-'
		PN+=$I
	   else
	        PV+="_$I"
	   fi
	done
	IFS='';
	echo $PN-$PV
}

# Reotrna el string usado para las optimizaciones del compilador.
# @param $1 : $ARCH . Ejemplo: i486
get_compiler_optimizations() {
# Slackware 11 and up need other option (gcc > 3.3.x)
	if [ $(gcc -dumpversion | tr -d  '.' |cut -c 1-2) -gt 33 ]; then
	MOPT=tune
	else
	MOPT=cpu
	fi
	case "$ARCH" in
	i386)      SLKCFLAGS="-O2 -march=i386 -m${MOPT}=i686"
		SLKLDFLAGS=""; LIBDIRSUFFIX="" ;;
	i486)      SLKCFLAGS="-O2 -march=i486 -m${MOPT}=i686"
		SLKLDFLAGS=""; LIBDIRSUFFIX="" ;;
	s390)      SLKCFLAGS="-O2"
		SLKLDFLAGS=""; LIBDIRSUFFIX="" ;;
	powerpc)   SLKCFLAGS="-O2"
		SLKLDFLAGS=""; LIBDIRSUFFIX="" ;;
	x86_64)    SLKCFLAGS="-O2 -fPIC"
		SLKLDFLAGS="-L/usr/lib64"; LIBDIRSUFFIX="64" ;;
	athlon-xp) SLKCFLAGS="-march=athlon-xp -O3 -pipe -fomit-frame-pointer"
		SLKLDFLAGS=""; LIBDIRSUFFIX="" ;;
	esac
	echo "$SLKCFLAGS"
}

# Cambia un algo de la forma: /var/tmp -> \/var\/tmp
quote_for_sed() { echo $1 | sed "s/\//\\\\\//g" ; }

if [ $(whoami) != 'root' ] ; then
  echo "ERROR: You need to be root for create packages..."
  exit 1
fi

# Set initial variables:
#Archivo comprimido con el source del programa:
SRC_FILE=$1
SRC_DIR=$(get_basename $SRC_FILE)
# Nombre del programa + version:
PKG_NAME_AND_VERSION=$(get_package_name $SRC_DIR)
# Nombre del programa
PGM_NAME=${PKG_NAME_AND_VERSION%-*}
# Version:
VERSION=${PKG_NAME_AND_VERSION##*-}
ARCH=${ARCH:-"noarch"}
BUILD=${BUILD:-"1leo"}

ACTUAL_DIR=$(pwd)
BUILD_DIR=${BUILD_DIR:-$ACTUAL_DIR}
PACKAGE_NAME=$PKG_NAME_AND_VERSION-$ARCH-$BUILD.tgz
INSTALL_TMP_DIR="/tmp/$SRC_DIR"
# Optimizaciones de compilacion dependientes de la arquitectura:
COMP_OPTIONS=$(get_compiler_optimizations $ARCH)
# Convertir en Absoluto el path a los Fuentes:
[ "${SRC_DIR:0:1}" == "." ] && SRC_DIR=${ACTUAL_DIR}/${SRC_DIR}

#echo "SRC_FILE            =$SRC_FILE"
#echo "SRC_DIR             =$SRC_DIR"
#echo "PKG_NAME_AND_VERSION=$PKG_NAME_AND_VERSION"
#echo "PKG_NAME            =$PKG_NAME"
#echo "VERSION             =$VERSION"
#echo "ARCH                =$ARCH"
#echo "BUILD               =$BUILD"
#echo "ACTUAL_DIR          =$ACTUAL_DIR"
#echo "BUILD_DIR           =$BUILD_DIR"
#echo "PACKAGE_NAME        =$PACKAGE_NAME"
#echo "INSTALL_TMP_DIR     =$INSTALL_TMP_DIR"
#echo "COMP_OPTIONS        =$COMP_OPTIONS"


#USR="smmsp"
#GRP="smmsp"

#ETCDIR="etc/rrdtool"

tar -xjf $SRC_FILE && \
{ # try to apply patchs... 
ls *.patch &>/dev/null && { cat *.patch |patch -p0 -d $SRC_DIR || exit 1 ;} || true
} && \
cd $SRC_DIR || { echo "Error descompresion del codigo fuente: $SRC_FILE" 1>&2 && exit 1 ; }

rm -rf $INSTALL_TMP_DIR &> /dev/null

# Patch the iptraf path:
sed -i -re 's#(my\s+\$iptraf\s*=\s*\S+)/bin/(.*)#\1/sbin/\2#' rrd_iptraf.pl

# Copy executable scripts:
mkdir -p $INSTALL_TMP_DIR/usr/bin && \
mv *.sh *.pl $INSTALL_TMP_DIR/usr/bin

# Copy config:
mkdir -p $INSTALL_TMP_DIR/etc/sysconfig && \
mv systemgraph.sysconfig $INSTALL_TMP_DIR/etc/sysconfig/systemgraph.sysconfig.new

# RRD Dir:
mkdir -p $INSTALL_TMP_DIR/var/lib/systemgraph

# WWW cgi:
mkdir -p $INSTALL_TMP_DIR/var/www/systemgraph && \
mv systemgraph.cgi $INSTALL_TMP_DIR/var/www/systemgraph
# Later we'll create the apache config file ;)

# Add documentation:
mkdir -p $INSTALL_TMP_DIR/usr/doc/$PKG_NAME_AND_VERSION
cp -r * \
  $INSTALL_TMP_DIR/usr/doc/$PKG_NAME_AND_VERSION
cp ../*.SlackBuild $INSTALL_TMP_DIR/usr/doc/$PKG_NAME_AND_VERSION
chown -R root:root $INSTALL_TMP_DIR/usr/doc/$PKG_NAME_AND_VERSION

cd $INSTALL_TMP_DIR && \

## Preparar los archivos de configuracion...
#( cd $ETCDIR && \
#  echo "Preparando los archivos de configuracion para upgrades..."
#  for I in * ; do
#     mv $I $I.new
#  done
#)

# --- OWNERSHIP, RIGHTS ---
chmod -R o-w *
chown -R root:root usr/bin etc var 2>/dev/null


# Apache Setup...
( mkdir -p etc/httpd/vhosts && \
  cd etc/httpd/vhosts && \
cat <<_EOF >> systemgraph.conf
Alias /systemgraph "/var/www/systemgraph"
<Directory "/var/www/systemgraph">
    # Honor .htaccess files:
    AllowOverride None
    DirectoryIndex index.php index.html systemgraph.cgi
    Options +ExecCGI
    AddHandler cgi-script .cgi .pl
    Order allow,deny
    Allow from all
    # Allow from 127.0.0.1
    # Allow from your-workstation.com
</Directory>
_EOF
)

# Add a post-install script:
mkdir -p install &&\
( cd install && \
cat <<EOINS > slack-desc
         |-----handy-ruler------------------------------------------------------|
$PGM_NAME: $PGM_NAME $VERSION (graphical system statistics)
$PGM_NAME:
$PGM_NAME: Nice graphical system statistics RRDTool frontend which produces
$PGM_NAME: graphs of various system data. It doesn't require snmp. It consists of
$PGM_NAME: some shell and perl scripts. You can query graph for personalized last
$PGM_NAME: time.
$PGM_NAME:
$PGM_NAME:
$PGM_NAME: Sitepage: http://www.decagon.de/sw/systemgraph/index.html
$PGM_NAME:
$PGM_NAME:
EOINS
#'

cat <<EOINS > doinst.sh
# Handle the incoming configuration files:
config() {
    NEW="\$1"
    OLD="\$(dirname \$NEW)/\$(basename \$NEW .new)"
# If there's no config file by that name, mv it over:
    if [ ! -f \$OLD ]; then
      mv \$NEW \$OLD
    elif [ ! -s \$NEW -o "\$(cat \$OLD | md5sum)" = "\$(cat \$NEW | md5sum)" ]; then
# toss the redundant copy
      rm -f \$NEW
    fi
}

config etc/sysconfig/systemgraph.sysconfig.new

# Add the crontab entris
grep -v ^# /usr/doc/$PKG_NAME_AND_VERSION/systemgraph.cron.d \
   | sed -re 's/(\*)\s+root/\1/' | while read LINE ; do
        CMD=\$(echo "\$LINE"|sed -re 's/.*\s+(\S+)$/\1/') #'
        grep -q "\$CMD" /var/spool/cron/crontabs/root \
        || echo "\$LINE" >> /var/spool/cron/crontabs/root
   done
# Tell to crond that this file has changed
echo "root" >> /var/spool/cron/crontabs/cron.update
#echo "REMEMBER to reload the cron daemon."

EOINS
)

##############
create_package $INSTALL_TMP_DIR $PACKAGE_NAME $BUILD_DIR && \
#exit 0
cd $ACTUAL_DIR && rm -rf $SRC_DIR || { echo "Terminado con Error" 1>&2 && exit 1 ;}


