#!/usr/bin/env bash
set -euo pipefail

INTERACTIVE=true

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --no-interactive)
            INTERACTIVE=false
            shift
            ;;
        *)
    esac
done

echo "This script will install the DJI Thermal SDK in your installation of PIX4Dengine SDK."
echo "The DJI Thermal SDK is not a PIX4D product, use it at your own risk."
if [[ $INTERACTIVE == true ]]; then
    read -p "Do you want to continue? [y/N] " -n 1 -r
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Aborted."
        exit 1
    fi
fi

# Ensure required commands exist
for cmd in python curl unzip grep mktemp patchelf realpath; do
    if ! command -v "$cmd" &>/dev/null; then
        echo "Command '$cmd' not found." >&2
        exit 1
    fi
done

# Discovering the output directory
if ! python -c "from pix4dvortex._pyext import _pyvtx" 2> /dev/null; then
   echo "PIX4Dengine SDK not found"
   exit 1
fi
TARGET_DIR=$(dirname $(python -c "from pix4dvortex._pyext import _pyvtx; print(_pyvtx.__file__)"))
PAGE_URL="https://www.dji.com/downloads/softwares/dji-thermal-sdk"

echo "Fetching download link..."
DOWNLOAD_URL=$(curl -sL "$PAGE_URL" | grep -oE 'https://[^"]+dji_thermal_sdk[^"]+\.zip' | head -n 1 || true)
# Fallback direct CDN URL if dynamic scraping fails
if [[ -z "$DOWNLOAD_URL" ]]; then
    echo "Could not automatically discover the download URL from https://www.dji.com/downloads/softwares/dji-thermal-sdk"
    exit -1
fi

TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT # Cleanup at exit

echo "Downloading archive..."
curl -fL --progress-bar "$DOWNLOAD_URL" -o "$TMP_DIR/dji_sdk.zip"

echo "Installing..."
unzip -q "$TMP_DIR/dji_sdk.zip" -d "$TMP_DIR/unpacked"
DJI_LIB_DIR="${TMP_DIR}/unpacked/tsdk-core/lib/linux/release_x64"
for DJI_LIB in "${DJI_LIB_DIR}"/lib*.so; do
    patchelf --force-rpath --set-rpath '$ORIGIN' ${DJI_LIB}
done
cp "${DJI_LIB_DIR}"/* "${TARGET_DIR}"

echo "DJI Thermal SDK successfully extracted to: $(realpath "$TARGET_DIR")"
