#!/bin/bash

set -exo pipefail

export PKGNAME=python3-telethon
API_URL=https://api.github.com/repos/tulir/Telethon/tags
JQ_EXPR='.[] | "\(.name[1:]) \(.tarball_url)"'


ROOT=$(pwd)
function fetch() {
    cd "${SRCDIR}"
    # WORKAROUND
    export VERSION=1.25.0a5
    git clone https://github.com/tulir/Telethon "telethon-${VERSION}"
    #mkdir -p "telethon-${VERSION}"
    #wget "${URL}" --output-document "telethon-${VERSION}.tar.gz"
    #tar -x -C "telethon-${VERSION}" --strip-components=1 -f "telethon-${VERSION}.tar.gz"
    #rm "telethon-${VERSION}.tar.gz"
}

function prepare() {
    mkdir -p \
          "${PKGDIR}/DEBIAN" \
	  "${PKGDIR}/usr/share/doc/${PKGNAME}"\
	  "${PKGDIR}/usr/lib/python3/dist-packages"
    cd "${SRCDIR}/telethon-${VERSION}"
    git checkout 23d38d49193f680f03f0545bbfa6ad3da83c29c1
    python3 setup.py egg_info install --root="${PKGDIR}/" --prefix=/usr --optimize=1
    rsync -a "${PKGDIR}/usr/local/lib/python3.11/dist-packages/" "${PKGDIR}/usr/lib/python3/dist-packages/"
    rm -rf "${PKGDIR}/usr/local/lib/python3.11/"
    find "${PKGDIR}/usr/lib/python3/dist-packages" -name __pycache__ -exec rm -r {} \; 2>/dev/null || true
    find "${PKGDIR}/usr/lib/python3/dist-packages" -name '*.pyc' -exec rm {} \;
    cp "${ROOT}/debian.control" "${PKGDIR}/DEBIAN/control"
    install -m 0644 "${SRCDIR}/telethon-${VERSION}/LICENSE" "${PKGDIR}/usr/share/doc/${PKGNAME}/copyright"
    sed -re "s/__VERSION__/${VERSION}/g" -i "${PKGDIR}/DEBIAN/control"
    sed -re "s/__MAINTAINER__/${MAINTAINER}/g" -i "${PKGDIR}/DEBIAN/control"
    find "${PKGDIR}" -exec touch -m --reference "${SRCDIR}/telethon-${VERSION}/telethon/version.py" {} \;
}

function package() {
    cd "${BUILDDIR}"
    dpkg-deb --build "${PKGDIR}" "${BUILDDIR}"
}

function build() {
    read VERSION URL <<<$(curl "${API_URL}" | jq -r "${JQ_EXPR}" | head -1)
    export VERSION
    export URL
    export BUILDDIR=${ROOT}/build
    export SRCDIR=${ROOT}/build/srcdir
    export PKGDIR=${ROOT}/build/pkgdir
    mkdir -p ${SRCDIR} ${PKGDIR}
    fetch
    prepare
    package
}
 

build