#!/bin/bash

CWD=$(pwd)

PRGNAM=$(basename "$CWD")
GITHUB_REPO=mozilla-mobile/mozilla-vpn-client
VERSION=${VERSION:-$(curl -s https://api.github.com/repos/${GITHUB_REPO}/tags | jq -r '.[0].name' | tr -d v)}
ARCH=$(uname -m)
BUILD=${BUILD:-1}
TAG=${TAG:-gwh}
TMP=${TMP:-/tmp/$TAG}
PKG=$TMP/pkg-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

REPOSITORY=${REPOSITORY:-/home/installs/SlackBuilds/_repositories/$PRGNAM}

UBUNTU_VERSION=jammy1
DEBARCH=amd64

mkdir -p "$REPOSITORY"

[ ! -e "$REPOSITORY"/"$PRGNAM-${VERSION}-${ARCH}.deb" ] && wget -c -O "$REPOSITORY"/"$PRGNAM-${VERSION}-${ARCH}.deb" \
                                                            "https://launchpad.net/~mozillacorp/+archive/ubuntu/mozillavpn/+files/mozillavpn_${VERSION}-${UBUNTU_VERSION}_${DEBARCH}.deb"

rm -fr "$PKG"
mkdir -p "$PKG"/

cd "$PKG"/ || exit 1
ar x "$REPOSITORY"/"$PRGNAM-${VERSION}-${ARCH}.deb"
rm debian-binary control.tar.zst

tar xvf data.tar.zst && rm data.tar.zst

mv usr/lib{,64}/

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} (A fast, secure and easy to use VPN. […] by […] Firefox.)
${PRGNAM}:
${PRGNAM}: One tap to privacy Surf, stream, game, and get work done while
${PRGNAM}: maintaining your privacy online. Whether you’re traveling, using
${PRGNAM}: public WiFi, or simply looking for more online security, we will
${PRGNAM}: always put your privacy first.
${PRGNAM}:
${PRGNAM}:
${PRGNAM}:
${PRGNAM}: https://vpn.mozilla.org/
${PRGNAM}: DEPENDS: qt6, md4c
EOF

cd "$PKG" || exit 1
chown -R root:root ./*
rm -f "$PKG"/{,usr/}lib"$(uname -m | grep -o 64)"/*.la
/sbin/makepkg -l y -c n "${OUTPUT}"/"${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.txz"