#!/bin/bash

CWD=$(pwd)

PRGNAM=$(basename $CWD)
VERSION=${VERSION:-$(curl "https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=minecraft-launcher" | grep "pkgver=" | grep -o "[0-9]*")}

ARCH=$(uname -m)
BUILD=${BUILD:-1}
TAG=${TAG:-gwh}
TMP=${TMP:-/tmp/$TAG}
PKG=$TMP/pkg-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

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

mkdir -p $REPOSITORY

[ ! -e $REPOSITORY/minecraft-launcher_${VERSION}.tar.gz ] && wget -c -O $REPOSITORY/minecraft-launcher_${VERSION}.tar.gz https://launcher.mojang.com/download/linux/x86_64/minecraft-launcher_${VERSION}.tar.gz
[ ! -e $REPOSITORY/minecraft-launcher.svg ] && wget -c -O $REPOSITORY/minecraft-launcher.svg https://launcher.mojang.com/download/minecraft-launcher.svg
rm -fr $PKG
mkdir -p $PKG/opt/${PRGNAM}

tar xvf $REPOSITORY/minecraft-launcher_${VERSION}.tar.gz -C $PKG/opt/

rm $REPOSITORY/minecraft-launcher_${VERSION}.tar.gz

mkdir -p $PKG/usr/bin
cd $PKG/usr/bin
ln -s ../../opt/minecraft-launcher/minecraft-launcher

mkdir -p $PKG/usr/share/icons/hicolor/symbolic/apps/
cp $REPOSITORY/minecraft-launcher.svg $PKG/usr/share/icons/hicolor/symbolic/apps/

mkdir -p $PKG/usr/share/applications/
cat <<EOF > $PKG/usr/share/applications/minecraft-launcher.desktop
[Desktop Entry]
Type=Application
Version=${VERSION}
Name=Minecraft Launcher
Comment=Official Minecraft Launcher
Exec=/opt/minecraft-launcher/minecraft-launcher
Path=/opt/minecraft-launcher/
Icon=minecraft-launcher
Terminal=false
Categories=Game;Application;
EOF
mkdir -p $PKG/install

cat <<EOF > $PKG/install/slack-desc
# 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 ':'.

         |-----handy-ruler------------------------------------------------------|
${PRGNAM}: ${PRGNAM} (Game)
${PRGNAM}:
${PRGNAM}: WHAT IS MINECRAFT?
${PRGNAM}: IT’S A GAME ABOUT PLACING BLOCKS AND GOING ON ADVENTURES
${PRGNAM}:
${PRGNAM}: It’s set in infinitely-generated worlds of wide open terrain - icy
${PRGNAM}: mountains, swampy bayous, vast pastures and much more - filled with
${PRGNAM}: secrets, wonders and peril!
${PRGNAM}:
${PRGNAM}:
${PRGNAM}: ${PRGNAM} home: http://minecraft.net/
EOF

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