#!/bin/bash

if [ -z "$1" ]; then
    echo "Usage: $0 <ORIGTARGZ>"
    exit 1
fi

set -e

UPSTREAM_TARBALL="$(realpath -s "$1")"

if [ ! -e "${UPSTREAM_TARBALL}" ]; then
    echo "Error: Upstream tarball not found"
    exit 1
fi

COMPONENT_NAME="dependencies"
COMPONENT_TARBALL="${UPSTREAM_TARBALL//.orig.tar/.orig-${COMPONENT_NAME}.tar}"

TEMP_DIR="$(mktemp -d)"

echo "Unpacking upstream tarball: ${UPSTREAM_TARBALL} into: ${TEMP_DIR}"
tar --strip-components=1 -xaf "${UPSTREAM_TARBALL}" -C "${TEMP_DIR}"

COMPONENT_DIR="${TEMP_DIR}/${COMPONENT_NAME}"
CMAKELISTS_FILE="${TEMP_DIR}/CMakeLists.txt"

# Get asmjit sources for required commit
DEPENDENCY_NAME="asmjit"
DEPENDENCY_DIR="${COMPONENT_DIR}/${DEPENDENCY_NAME}"

COMMIT_ID=$(grep -E "set.ASMJIT_GIT_TAG *\"[0-9a-f]*\"" "${CMAKELISTS_FILE}" | cut -d'"' -f2)
ARCHIVE_URL="https://github.com/asmjit/asmjit/archive/${COMMIT_ID}.tar.gz"
ARCHIVE_FILE="${TEMP_DIR}/${DEPENDENCY_NAME}.tar.gz"

echo "Creating directory: ${DEPENDENCY_DIR}"
mkdir -p "${DEPENDENCY_DIR}"

echo "Downloading: ${DEPENDENCY_NAME}"
wget "${ARCHIVE_URL}" -O "${ARCHIVE_FILE}"

echo "Unpacking: ${DEPENDENCY_NAME}"
tar --strip-components=1 -xaf "${ARCHIVE_FILE}" -C "${DEPENDENCY_DIR}"

# Get blend2d sources for required commit
DEPENDENCY_NAME="blend2d"
DEPENDENCY_DIR="${COMPONENT_DIR}/${DEPENDENCY_NAME}"

COMMIT_ID=$(grep -E "set.BLEND2D_GIT_TAG *\"[0-9a-f]*\"" "${CMAKELISTS_FILE}" | cut -d'"' -f2)
ARCHIVE_URL="https://github.com/blend2d/blend2d/archive/${COMMIT_ID}.tar.gz"
ARCHIVE_FILE="${TEMP_DIR}/${DEPENDENCY_NAME}.tar.gz"

echo "Creating directory: ${DEPENDENCY_DIR}"
mkdir -p "${DEPENDENCY_DIR}"

echo "Downloading: ${DEPENDENCY_NAME}"
wget "${ARCHIVE_URL}" -O "${ARCHIVE_FILE}"

echo "Unpacking: ${DEPENDENCY_NAME}"
tar --strip-components=1 -xaf "${ARCHIVE_FILE}" -C "${DEPENDENCY_DIR}"

echo "Creating component tarball: ${COMPONENT_TARBALL}"
cd "${TEMP_DIR}" || exit 1
tar --owner root --group root -caf "${COMPONENT_TARBALL}" "${COMPONENT_NAME}"
cd "${OLDPWD}" || exit 1

echo "Removing temporary directory: ${TEMP_DIR}"
rm -rf "${TEMP_DIR}"
