#!/usr/bin/env bash

# Function to display help message
show_help() {
  echo "Usage: $0 [options] builddir dsc_file"
  echo
  echo "Options:"
  echo " -h, --help     Show this help message and exit."
  echo " builddir       The directory where the build will take place."
  echo " dsc_file       The URL or path to the .dsc file for the package to build."
  echo
  echo "Example:"
  echo " $0 /path/to/builddir https://example.com/path/to/package.dsc"
  exit 0
}

# Check if the first argument is -h or --help
if [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
  show_help
fi

# Check if exactly two arguments are provided
if [ $# -ne 2 ]; then
  echo "Error: Exactly two arguments are required."
  show_help
fi

# Check if the second argument ends with .dsc
if [[ ! "$2" =~ \.dsc$ ]]; then
  echo "Error: The second argument must end with .dsc."
  show_help
fi

BUILDDIR=$1
DSC_FILE=$2

apt install -y git-buildpackage equivs

if [ "$1" == "-h" ]; then
  echo "Usage: $(basename $0) Takes a builddir and a dsc url and builds and installs the result."
  exit 0
fi

FILESTAMP=$(date '+%Y-%m-%d-%H-%M')-$(uuidgen -t)
BUILD_DIR=${BUILDDIR}/build-${FILESTAMP}

echo "Building in ${BUILD_DIR}"
mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}" || ezit

# Download the package to build
echo "RUNNING: gbp import-dsc -v --allow-unauthenticated ${DSC_FILE}"
gbp import-dsc -v --allow-unauthenticated "${DSC_FILE}"

if [ $? -ne 0 ]; then
  echo "gbp import-dsc failed to connect."
  exit 1
fi

cd * || exit

# Install the build deps
mk-build-deps debian/control --install --root-cmd sudo --remove

# Build the packages
if [ -d debian/watch ]; then
  # dpkg-buildpackage -us -uc -b
  export lang=en_GB.UTF-8
  gbp import-orig --pristine-tar --uscan

fi

# if [ -f *.deb ]; then
# 	dpkg -i ../*.deb
# 	apt install -y -f
# else
# 	echo "No debs to install, did the package build complete successfully?"
# fi

# gbp buildpackage --git-pristine-tar --git-ignore-new --git-export-dir=".." -us -uc
