#!/bin/bash

# variables
GITHUB_REPO=FreeTubeApp/FreeTube
VERSION=${VERSION:-trunk}

BUILD=${BUILD:-2}

TAG=gwh
OUTPUT=/tmp
TMP=/tmp/$TAG
CWD=$(pwd)

PKGNAM=$(basename "$CWD")
PKG=$TMP/pkg-$PKGNAM

ARCH=$(uname -m)

REPOSITORY=/home/installs/SlackBuilds/_repositories/$PKGNAM
PREFIX=/usr

# nettoyage préalable
rm -fr "$PKG" "${TMP:?}/$PKGNAM"

mkdir -p "$PKG"

# mise en place
[ ! -e "$REPOSITORY" ] && git clone https://github.com/${GITHUB_REPO} "$REPOSITORY"
cd "$REPOSITORY" || exit 1
git pull --all

cp -R "$REPOSITORY" $TMP/
cd "$TMP/$PKGNAM/" || exit 1

case $VERSION in
    trunk)
        PKGVERSION="r$(git rev-list --count HEAD)_$(git log -1 --format=%h)"
        ;;
    latest)
        PKGVERSION=$(git tag --sort=-version:refname | head -n1)
        git checkout "$VERSION"
        ;;
    *)
        PKGVERSION="$VERSION"
        git checkout "$VERSION"
        ;;
esac

yarn install

sed -i "s|deb', 'zip', '7z', 'apk', 'rpm', 'AppImage', 'pacman|zip|" _scripts/build.js

npm run build

mkdir -p "$PKG/opt/$PKGNAM"
cd "$PKG/opt/$PKGNAM" || exit 1
unzip "$TMP/$PKGNAM/build/freetube*.zip"

mkdir -p "$PKG$PREFIX/bin"
cd "$PKG$PREFIX/bin" || exit 1
ln -s "../../opt/$PKGNAM/freetube" freetube

cd "$TMP/$PKGNAM/" || exit 1

mkdir -p "$PKG$PREFIX/share/icons/hicolor/scalable/apps/"
cp _icons/icon.svg "$PKG$PREFIX/share/icons/hicolor/scalable/apps/freetube.svg"

mkdir -p "$PKG$PREFIX/share/applications/"
cat <<EOF > "$PKG$PREFIX/share/applications/freetube.desktop"
[Desktop Entry]
Name=FreeTube
Exec=/opt/$PKGNAM/freetube %U
Terminal=false
Type=Application
Icon=freetube
StartupWMClass=FreeTube
Comment=A private YouTube client
MimeType=x-scheme-handler/freetube;
Categories=Network;
EOF

mkdir -p "$PKG$PREFIX/doc/$PKGNAM"
cp LICENSE ./*.md "$PKG$PREFIX/doc/$PKGNAM/"

# correction
cd "$PKG" || exit 1
chown -R root:root ./*

# embaumement
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------------------------------------------------------|
freetube: freetube (The Private YouTube Client)
freetube:
freetube: FreeTube is a YouTube client for Windows, Mac, and Linux built around
freetube: using YouTube more privately. You can enjoy your favorite content and
freetube: creators without your habits being tracked.
freetube:
freetube:
freetube:
freetube:
freetube: Homepage: https://freetubeapp.io/
freetube:
EOF

# empaquetage
/sbin/makepkg --linkadd y --chown n --prepend "$OUTPUT/$PKGNAM-$PKGVERSION-$ARCH-$BUILD$TAG.txz"