#!/bin/bash
set -x

PRGNAM=$(basename $(pwd))

# Fetching sources
VERSION=${VERSION:-1.16.7}

BUILD=1

ARCH=$(uname -m)
LIBSUFFIX=$(echo $ARCH | grep -o "\(64\)")

CWD=$(pwd)
TAG=gwh
OUTPUT=/tmp
TMP=/tmp/$TAG
PKG=$TMP/pkg-$PRGNAM

PREFIX=/usr

REPOSITORY=${REPOSITORY:-/var/cache/SlackBuilds.gwh/$PRGNAM}

mkdir -p $REPOSITORY

mkdir -p $TMP

# Cleaning
rm -fr $TMP/$PRGNAM $PKG

[ ! -e $REPOSITORY/makemkv-bin-$VERSION.tar.gz ] && wget -c https://www.makemkv.com/download/makemkv-bin-$VERSION.tar.gz -O $REPOSITORY/makemkv-bin-$VERSION.tar.gz
[ ! -e $REPOSITORY/makemkv-oss-$VERSION.tar.gz ] && wget -c https://www.makemkv.com/download/makemkv-oss-$VERSION.tar.gz -O $REPOSITORY/makemkv-oss-$VERSION.tar.gz

# Preparation
mkdir -p $TMP/$PRGNAM
cd $TMP/$PRGNAM

tar xvf $REPOSITORY/makemkv-bin-$VERSION.tar.gz
tar xvf $REPOSITORY/makemkv-oss-$VERSION.tar.gz

chown -R root:root .
find . \
     \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 555 -o -perm 511 \) \
     -exec chmod 755 {} \; -o \
     \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) \
     -exec chmod 644 {} \;

cd makemkv-bin-$VERSION
make install DESTDIR=$PKG

cd ../makemkv-oss-$VERSION

# Configuration
./configure \
    --prefix=$PREFIX \
    --mandir=$PREFIX/man \
    --libdir=$PREFIX/lib$(echo "$ARCH" | grep -o "64") \
    --sysconfdir=/etc

# Building
make

# Installation
make install DESTDIR=$PKG

mkdir -p $PKG$PREFIX/share/$PRGNAM
cp License.txt $PKG$PREFIX/share/$PRGNAM
find . -name "*.bz2" -exec bunzip2 {} \;

# Cleaning
cd $PKG
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

[ -d $PKG$PREFIX/man ] && find $PKG$PREFIX/man -type f -name "*.?" -exec gzip -9 {} \;

chown -R root:root .
find . \
     \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 555 -o -perm 511 \) \
     -exec chmod 755 {} \; -o \
     \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) \
     -exec chmod 644 {} \;

# Packaging
mkdir install
cat <<EOF > install/slack-desc
$PRGNAM: $PRGNAM (Video ripper)
$PRGNAM:
$PRGNAM: Needs a monthly key from
$PRGNAM: https://www.makemkv.com/forum/viewtopic.php?t=1053
$PRGNAM:
$PRGNAM:
$PRGNAM:
$PRGNAM:
$PRGNAM:
$PRGNAM: https://www.makemkv.com/forum/viewforum.php?f=3
$PRGNAM:
EOF

rm -f $PKG/{,usr/}lib$(uname -m | grep -o 64)/*.la
/sbin/makepkg --linkadd y --chown n --prepend $OUTPUT/$PRGNAM-$(echo $VERSION | tr -d '-')-$ARCH-$BUILD$TAG.txz