#!/bin/bash
set -x
set -euo pipefail

echo "debian python tooling not working for packaging pypi"
exit 1

# sudo apt update
# sudo apt install -y cookiecutter git devscripts jq

# Check dependencies
for cmd in cookiecutter git jq uscan; do
  if ! command -v "$cmd" &>/dev/null; then
    echo "Error: $cmd is not installed."
    exit 1
  fi
done

# Package details (modify as needed)
PACKAGE_OWNER="elParaguayo"
PACKAGE_NAME="qtile-extras"
BUILD_DIR="/var/tmp/build_${PACKAGE_NAME}"
UPSTREAM_REPO="https://github.com/${PACKAGE_OWNER}/${PACKAGE_NAME}"
DEBIANIZED_MOLD_REPO="https://github.com/Springerle/debianized-pypi-mold.git"
OUTPUT_DIR="${PACKAGE_NAME}-debian"
SRC_DIR="${BUILD_DIR}/${OUTPUT_DIR}/${PACKAGE_NAME}"
VERSION=$(curl -s "https://pypi.org/pypi/${PACKAGE_NAME}/json" | jq -r '.info.version')

# Create and enter build directory
mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}" || exit 1

# Clone mold if missing
if [ ! -d "debianized-pypi-mold" ]; then
  git clone "$DEBIANIZED_MOLD_REPO"
fi

conf_print_watch4() {
  cat <<EOF
version=5
opts=filenamemangle=s/.+\/v?(\d\S*)\.tar\.gz/${PACKAGE_NAME}-z\$1\.tar\.gz/ \
https://github.com/${PACKAGE_OWNER}/${PACKAGE_NAME}/releases \
.*/archive/refs/tags/v?(\d\S*)\.tar\.gz
EOF
}
# mkdir -p "${SRC_DIR}/debian"
# conf_print_watch4 | tee ${SRC_DIR}/debian/watch

conf_print_watch5() {
  cat <<EOF
version=5

Template: GitHub
Owner: ${PACKAGE_OWNER}
Project: ${PACKAGE_NAME}   
EOF
}
# mkdir -p "${SRC_DIR}/debian"
# conf_print_watch5 | tee ${SRC_DIR}/debian/watch

: "${DEBFULLNAME:="Cyteen May"}"
: "${DEBMAIL:="cyteen.may@ring-zero.co.uk"}"

# ✅ Fixed variable expansion and clean argument list
echo "Generating Debian package for ${PACKAGE_NAME} (version ${VERSION})..."
cookiecutter \
  --output-dir "$OUTPUT_DIR" \
  --overwrite-if-exists \
  debianized-pypi-mold/ \
  package_name="$PACKAGE_NAME" \
  repo_name="$PACKAGE_NAME" \
  upstream_repo_github="$PACKAGE_OWNER/${PACKAGE_NAME}" \
  version="$VERSION" \
  maintainer_name="${DEBFULLNAME}" \
  maintainer_email="${DEBMAIL}" \
  license="MIT" \
  python_version="3" \
  debhelper_compat="13" \
  has_watch="y"
#  --no-input

# Verify directory was created correctly
if [ ! -d "${OUTPUT_DIR}/${PACKAGE_NAME}" ]; then
  echo "Error: Generated package directory not found!"
  exit 1
fi

# Enter generated directory
cd "${OUTPUT_DIR}/${PACKAGE_NAME}" || exit 1

# Download upstream source
echo "Downloading upstream source..."
uscan --download-current-version --force-download --verbose

# Build package
echo "Building Debian package..."
cd ..
tar -xf "${PACKAGE_NAME}_${VERSION}.orig.tar.gz"
cd "${PACKAGE_NAME}-${VERSION}" || exit 1
cp -r "../${PACKAGE_NAME}/debian" .
debuild -b -us -uc # -b builds only binary packages (faster)

# Cleanup (preserves final packages)
echo "Cleaning up temporary files..."
cd ..
rm -rf "${PACKAGE_NAME}-${VERSION}" "${PACKAGE_NAME}_${VERSION}.orig.tar.gz"

echo -e "\n✅ Success! Debian packages are in ${BUILD_DIR}/${OUTPUT_DIR}/"
