#!/bin/sh
# Purpose: prepare the orig tarball, but not dsc or debian which can be pulled by OBS directly

WORKDIR="${WORKDIR:-/usr/src/jellyfin-desktop/tmp}"
CACHEDIR="${CACHEDIR:-/usr/src/jellyfin-desktop/cache}"
OUTDIR="${OUTDIR:-/usr/src/jellyfin-desktop/prepared}"
ARCH="${ARCH:-linux64}"
VERSION="${VERSION:-0.0.0}"

mkdir -p "${WORKDIR}" ; cd "${WORKDIR}"

# step 1 get jellyfin-desktop source
git clone --recurse-submodules https://github.com/jellyfin/jellyfin-desktop jellyfin-desktop
cd jellyfin-desktop || { echo "Cannot cd to cloned directory. Aborted." 1>&2 ; exit 1 ; }

# download cef binary
(
    cd third_party ; mkdir cef ; cd cef ;
    cef_file="$( curl https://cef-builds.spotifycdn.com/index.json 2>/dev/null | jq --raw-output ".${ARCH}.versions[] | select(.cef_version == \"$( cat ../../CEF_VERSION )\") | .files[] | select(.type == \"minimal\").name" 2>/dev/null )"
    test -z "${cef_file}" && { echo "Cannot pull cef binary file. Check https://cef-builds.spotifycdn.com/index.html#linux64 and index.json manually. Aborted." 1>&2 ; exit 1 ; }
    cef_url="https://cef-builds.spotifycdn.com/${cef_file}"
    mkdir -p "${CACHEDIR}"
    wget --continue --output-document "${CACHEDIR:+${CACHEDIR%%/}/}${cef_file}" "${cef_url}"
    tar --exclude='**/.git' --strip-components=1 -xf "${CACHEDIR:+${CACHEDIR%%/}/}${cef_file}"
)

# compress the orig.tar.gz
cd ..
mkdir -p "${OUTDIR}"
tar -zcf "${OUTDIR:+${OUTDIR%%}/}jellyfin-desktop_${VERSION}.orig.tar.gz" jellyfin-desktop

# CLEAN UP
if test -z "${NO_CLEAN}" ; then
    rm -rf "${WORKDIR:-/usr/src/jellyfin-desktop/tmp}"
fi
