#!/bin/bash

# Slackware build script for <7zip>
# Copyright 2022-2024 Zhu, Qun-Ying
# 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.

cd $(dirname $0) ; CWD=$(pwd)

PRGNAM=7zip
VERSION=${VERSION:-25.01}
SRC_FILE="7z2501-src.tar.xz"
BUILD=${BUILD:-1}
TAG=${TAG:-_SBo}
PKGTYPE=${PKGTYPE:-tgz}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp/SBo}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

set -e

case "$ARCH" in
  "i586") makefile_name="cmpl_gcc_x86.mak" ;;
  "x86_64") makefile_name="cmpl_gcc_x64.mak" ;;
  *)        makefile_name="cmpl_gcc_${ARCH}.mak" ;;
esac

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
mkdir -p $PRGNAM-$VERSION/build
tar xvf $CWD/$SRC_FILE -C $PRGNAM-$VERSION
cd $PRGNAM-$VERSION
chmod -R a=r,u+w,a+X .
SRC_DIR=$TMP/$PRGNAM-$VERSION
export BUILD_DIR="${SRC_DIR}/build"
sed -i 's|MY_ASM = asmc|MY_ASM = uasm|g' CPP/7zip/7zip_gcc.mak
sed -i 's|O=b/g_$(PLATFORM)|O=$(BUILD_DIR)|g' CPP/7zip/var_gcc_*.mak

BUNDLE_DIR=${SRC_DIR}/CPP/7zip/Bundles
cd ${BUNDLE_DIR}/Alone2
make -f ${SRC_DIR}/CPP/7zip/${makefile_name}

cd ${BUNDLE_DIR}/SFXCon
make -f makefile.gcc

mkdir -p $PKG/usr/bin
install -Dm755 ./_o/7zCon $PKG/usr/bin
install -Dm755 --strip $BUILD_DIR/7zz $PKG/usr/bin
(cd $PKG/usr/bin; ln -s 7zz 7z)

cd $SRC_DIR

mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp DOC/* $PKG/usr/doc/$PRGNAM-$VERSION
cat $CWD/$PRGNAM.SlackBuild > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.$PKGTYPE
