#!/usr/bin/bash

# Copyright 2008, 2009  Patrick J. Volkerding, Sebeka, Minnesota, USA
# All rights reserved.

# Modified by rbistolfi and kidd for VectorLinux. All changes are public domain.

# This script assumes it will be launched within "/NAME/VERSION/src" dir.
# With all sources in "src" Your Vector Linux .txz package, slack-desc,
# and slack-required will be found in "VERSION" dir. The extraction and
# build will be in a temp dir created in "NAME" dir, and then removed on exit.
# Comment out second to last line to keep this dir intact.
#
# This Template was compiled from the contributions of many users of the Vector
# Linux forum at http://forum.vectorlinux.com and from tidbits collected 
# from all over the internet. 
#
# Please put your name below if you add some original scripting lines.
# AUTHORS = 

NAME="vim"            #Enter package Name!
VERSION=${VERSION:-"7.4"}      #Enter package Version!
VIMVER=74
VL_PACKAGER=${VL_PACKAGER:-"rbistolfi"}   #Enter your Name!
LINK=${LINK:-"ftp://ftp.$NAME.org/pub/$NAME/unix/$NAME-$VERSION.tar.bz2"}  #Enter URL for package here!
PATCHES=${PATCHES:-"ftp://ftp.$NAME.org/pub/$NAME/patches/$VERSION/"}
PYVER=$(python -V 2>&1 | cut -f 2 -d' ' | cut -f 1-2 -d.)

#SYSTEM VARIABLES
#----------------------------------------------------------------------------
BUILDNUM=${BUILDNUM:-"1"}
VL_VERSION=${VL_VERSION:-"$(ls /var/log/packages/|grep vlconfig2|cut -d "-" -f4|cut -c 2-5)"}
BUILD=${BUILD:-"$BUILDNUM""$VL_VERSION"}
ARCH=${ARCH:-"$(uname -m)"}

CONFIG_OPTIONS=${CONFIG_OPTIONS:-"--enable-pythoninterp \
--enable-perlinterp \
--disable-tclinterp \
--enable-multibyte \
--enable-cscope \
--with-features=huge \
--without-x \
--disable-gui \
--with-compiledby='rbistolfi@gmail.com'"}

LDFLAG_OPTIONS=${LDFLAG_OPTIONS:-""}
ADDRB=${ADDRB:-"ctags"} #Add deps that need to be added to the slack-required file here
EXRB=${EXRB:-""} #Add deps that need to be excluded from the slack-required file here
MAKEDEPENDS=${MAKEDEPENDS:-"ctags rsync"} #Add deps needed TO BUILD this package here.
#----------------------------------------------------------------------------

# DO NOT EXECUTE if NORUN is set to 1
if [ "$NORUN" != "1" ]; then

#SETUP PACKAGING ENVIRONMENT
#--------------------------------------------
CWD=$(pwd)
cd ../
RELEASEDIR=$(pwd)
cd $CWD
mkdir -p $RELEASEDIR/tmp
TMP=$RELEASEDIR/tmp
PKG=$TMP/package-$NAME
#--------------------------------------------



if [ $UID != 0 ]; then
   echo "You are not authorized to run this script. Please login as root"
   exit 1
fi

if [ ! -x /usr/bin/requiredbuilder ]; then
   echo "Requiredbuilder not installed, or not executable."
   exit 1
fi

if [ $VL_PACKAGER = "YOURNAME" ]; then
   echo 'Who are you?
   Please edit VL_PACKAGER=${VL_PACKAGER:-YOURNAME} in this script.
   Change the word "YOURNAME" to your VectorLinux packager name.
   You may also export VL_PACKAGER, or call this script with
   VL_PACKAGER="YOUR NAME HERE"'
   exit 1
fi


#CFLAGS SETUP
#--------------------------------------------
if [[ "$ARCH" = i?86 ]]; then
  ARCH=i586
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  CONFIGURE_TRIPLET="i586-vector-linux"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fpic"
  CONFIGURE_TRIPLET="x86_64-vlocity-linux"
  LIBDIRSUFFIX="64"
elif [ "$ARCH" = "powerpc" ]; then
  SLKCFLAGS="-O2"
  CONFIGURE_TRIPLET="powerpc-vlocity-linux"
  LIBDIRSUFFIX=""
fi

export CFLAGS="$SLKCFLAGS $CFLAG_OPTIONS"
export CXXFLAGS=$CFLAGS
export LDFLAGS="$LDFLAGS $LDFLAG_OPTIONS"
#--------------------------------------------


#GET THE SOURCE
#--------------------------------------------
for SRC in $(echo $LINK);do
if [ ! -f $(basename $SRC) ]
then
        wget -c $SRC
fi
done

#GET THE PATCHES
if [ ! -d $CWD/patches/ ]
then
	wget -c -r -nd -P patches $PATCHES
fi
#--------------------------------------------

# Determine VIM patchlevel:
if [ -d $CWD/patches ] ; then
  cd $CWD/patches
  PATCHLEVEL=$(cat README |awk {'print $2'}| tail -1 | cut -f 3 -d .)
#  PATCHLEVEL=$(/bin/ls ${VERSION}* 2> /dev/null | tail -1 | cut -f 3 -d . )
    if [ "$PATCHLEVEL" = "" ]; then
      PATCHLEVEL=000
    fi
  cd $CWD
fi

#REMOVE OLD BUILD
rm -rf $PKG
mkdir -p $PKG
cd $TMP
rm -rf ${NAME}${VIMVER}


#EXTRACT SOURCES
#-----------------------------------------------------
echo "Extracting source..."
tar xvf $CWD/$NAME-$VERSION.tar.* || exit 1
#-----------------------------------------------------


cd $TMP/${NAME}${VIMVER}

# Put any Patches here
#-----------------------------------------------------
#for file in $CWD/patches/${VERSION}* ; do
#	( patch -p0 --verbose --batch < $file )
#done
for p in $CWD/patches/${VERSION}.???; do 
	echo "Applying patch $(basename $p)"
#        mkdir -p $PKG/usr/doc/$NAME-$VERSION/patches/
#	cp $p $PKG/usr/doc/$NAME-$VERSION/
	patch -Np0 --quiet -i $p --batch || exit 1
done
# And now for patches > 1000,
for p in $CWD/patches/${VERSION}.????; do
	echo "Applying patch $(basename $p)"
#        mkdir -p $PKG/usr/doc/$NAME-$VERSION/patches/
#        cp $p $PKG/usr/doc/$NAME-$VERSION/
	patch -Np0 --quiet -i $p --batch || exit 1
done
#-----------------------------------------------------

# If there's no syntax update, create one:
if ! ls $CWD/vim-runtime-syntax-* 1> /dev/null 2> /dev/null ; then
  rm -rf runtime/syntax.orig
  cp -a runtime/syntax runtime/syntax.orig
  echo "Fetching vim syntax updates from ftp.nluug.nl..."
  rsync -avzcP ftp.nluug.nl::Vim/runtime/syntax/ runtime/syntax/ || exit 1
  diff -u -r --new-file runtime/syntax.orig runtime/syntax | \
	  gzip -9c > $CWD/vim-runtime-syntax-$(date +%Y%m%d).diff.gz
  rm -rf runtime/syntax
  mv runtime/syntax.orig runtime/syntax
fi

# Apply the syntax update:
zcat $CWD/vim-runtime-syntax-*.diff.gz | patch -p0 --verbose || exit 1


#SET PERMISSIONS
#-----------------------------------------
echo "Setting permissions..."
chown -R root:root .
find . -perm 664 -exec chmod 644 {} \;
find . -perm 777 -exec chmod 755 {} \;
find . -perm 2777 -exec chmod 755 {} \;
find . -perm 775 -exec chmod 755 {} \;
find . -perm 2755 -exec chmod 755 {} \;
find . -perm 774 -exec chmod 644 {} \;
find . -perm 666 -exec chmod 644 {} \;
find . -perm 600 -exec chmod 644 {} \;
find . -perm 444 -exec chmod 644 {} \;
find . -perm 400 -exec chmod 644 {} \;
find . -perm 440 -exec chmod 644 {} \;
find . -perm 511 -exec chmod 755 {} \;
find . -perm 711 -exec chmod 755 {} \;
find . -perm 555 -exec chmod 755 {} \;
#-----------------------------------------



#CONFIGURE & MAKE
#----------------------------------------------------------------------
# If you are building a KDE-related app, then change the following
# arguments in the script below:
# --prefix=$(kde-config -prefix) \
# --sysconfdir=/etc/kde \
#
# Making these changes will ensure that your package will build in the
# correct path and that it will work seamlessly within the KDE environment.
#
#-----------------------------------------------------------------------

# "Configuring source..."
./configure --prefix=/usr \
  --libdir=/usr/lib${LIBDIRSUFFIX} \
  --with-python-config-dir=/usr/lib${LIBDIRSUFFIX}/python$PYVER/config \
  --sysconfdir=/etc \
  --localstatedir=/var \
  --mandir=/usr/man \
  --program-prefix="" \
  --program-suffix="" \
  --build=$CONFIGURE_TRIPLET \
  $CONFIG_OPTIONS || exit 1

make || exit 1

make install DESTDIR=$PKG || exit

#######################################################################
#Miscellenious tweaks and things outside a normal ./configure go here #
#######################################################################

cp -a runtime/vimrc_example.vim runtime/vimrc.new

# This patch fixes a problem with vim and crontab -e as root
patch -p0 --verbose <$CWD/vim.vimrc.diff || exit 1
cat runtime/vimrc.new > $PKG/usr/share/vim/vimrc.new

# Legacy binary links:
( cd $PKG/usr/bin ; rm -rf ex )
( cd $PKG/usr/bin ; ln -sf vim ex )
( cd $PKG/usr/bin ; rm -rf rview )
( cd $PKG/usr/bin ; ln -sf vim rview )
( cd $PKG/usr/bin ; rm -rf rvim )
( cd $PKG/usr/bin ; ln -sf vim rvim )
( cd $PKG/usr/bin ; rm -rf view )
( cd $PKG/usr/bin ; ln -sf vim view )
( cd $PKG/usr/bin ; rm -rf eview )
( cd $PKG/usr/bin ; ln -sf vim eview )
( cd $PKG/usr/bin ; rm -rf evim )
( cd $PKG/usr/bin ; ln -sf vim evim )
( cd $PKG/usr/bin ; rm -rf vi )
( cd $PKG/usr/bin ; ln -sf vim vi )

mkdir -p $PKG/usr/doc/vim-$VERSION.$PATCHLEVEL
cp -a README.txt $PKG/usr/doc/$NAME-$VERSION.$PATCHLEVEL/README.txt
find $PKG/usr/doc/$NAME-$VERSION.$PATCHLEVEL -type f | xargs chmod 644
( cd $PKG/usr/doc/$NAME-$VERSION.$PATCHLEVEL ; rm -rf doc )
( cd $PKG/usr/doc/$NAME-$VERSION.$PATCHLEVEL ; ln -sf /usr/share/vim/vim$VIMVER doc )

cat $CWD/$NAME.SlackBuild > $PKG/usr/doc/$NAME-$VERSION.$PATCHLEVEL/$NAME.SlackBuild

#----------------------------------------------------------------------

# Fix manpage symlinks:
if [ -d $PKG/usr/man ]; then
  ( cd $PKG/usr/man
    for manpagedir in $(find . -type d -name "man*") ; do
      ( cd $manpagedir
        for eachpage in $( find . -type l -maxdepth 1) ; do
          ln -s $( readlink $eachpage ).gz $eachpage.gz
          rm $eachpage
        done
        gzip -9 *.?
      )
    done
  )
fi


mkdir -p $PKG/install

cat << EOF > $PKG/install/doinst.sh
#!/bin/sh
config() {
  NEW="\$1"
  OLD="\$(dirname \$NEW)/\$(basename \$NEW .new)"
  # If there's no config file by that name, mv it over:
  if [ ! -r \$OLD ]; then
    mv \$NEW \$OLD
  elif [ "\$(cat \$OLD | md5sum)" = "\$(cat \$NEW | md5sum)" ]; then # toss the redundant copy
    rm \$NEW
  fi
  # Otherwise, we leave the .new copy for the admin to consider...
}
config usr/share/vim/vimrc.new
EOF


#if there is a slack-desc in src dir use it
if test -f $CWD/slack-desc; then
cp $CWD/slack-desc $RELEASEDIR/slack-desc
else
# This creates the white space in front of "handy-ruler" in slack-desc below.

LENGTH=$(expr length "$NAME")
SPACES=0
SHIM=""
until [ "$SPACES" = "$LENGTH" ]; do
SHIM="$SHIM "
let SPACES=$SPACES+1
done

# Fill in the package summary between the () below.
# Then package the description, License, Author and Website.
# There may be no more then 11 $NAME: lines in a valid slack-desc.

cat > $RELEASEDIR/slack-desc << EOF
# HOW TO EDIT THIS FILE:
# The "handy ruler" below makes it easier to edit a package description.  Line
# up the first '|' above the ':' following the base package name, and the '|'
# on the right side marks the last column you can put a character in.  You must
# make exactly 11 lines for the formatting to be correct.  It's also
# customary to leave one space after the ':'.

$SHIM|-----handy-ruler------------------------------------------------------|
$NAME: $NAME (Vi IMproved)
$NAME:
$NAME: Vim is an almost compatible version of the UNIX editor vi.  Many new
$NAME: features have been added:  multi level undo, command line history,
$NAME: filename completion, block operations, and more.
$NAME:
$NAME:
$NAME: License: GPL
$NAME: Authors: Bram Moolenaar
$NAME: Website: www.vim.org

EOF
fi
cat >> $RELEASEDIR/slack-desc << EOF



#----------------------------------------
BUILDDATE: $(date)
PACKAGER:  $VL_PACKAGER
HOST:      $(uname -srm)
DISTRO:    $(cat /etc/vector-version)
CFLAGS:    $CFLAGS
LDFLAGS:   $LDFLAGS
CONFIGURE: $(awk "/\.\/configure\ /" $TMP/$NAME-$VERSION/config.log)

EOF

cat $RELEASEDIR/slack-desc > $PKG/install/slack-desc

#STRIPPING
#------------------------------------------------------------------------------------------------------------------
cd $PKG
echo " "
echo "Stripping...."
echo " "
find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
#------------------------------------------------------------------------------------------------------------------


#FINISH PACKAGE
#--------------------------------------------------------------
echo "Finding dependencies..."
ADD="$ADDRB" EXCLUDE="$EXRB" requiredbuilder -v -y -s $RELEASEDIR $PKG
mv $RELEASEDIR/slack-required $RELEASEDIR/slack-required_vim
echo "Creating package $NAME-$VERSION-$ARCH-$BUILD.txz"
makepkg -l y -c n $RELEASEDIR/$NAME-$VERSION.$PATCHLEVEL-$ARCH-$BUILD.txz

cd $CWD
echo "Cleaning up temp files..." && rm -rf $TMP
echo "Package Complete"
fi
#--------------------------------------------------------------

# vim: set tabstop=4 shiftwidth=4 foldmethod=marker : ##
