set -exo pipefail

ROOT=$(pwd)

pip3 install --break-system-packages maubot


function fetch() {
    cd "${SRCDIR}"
    git clone "${REPO}"
}

function prepare() {
    mkdir -p \
          "${PKGDIR}/DEBIAN" \
          "${PKGDIR}/usr/lib/maubot/plugins"
    PLUGIN_DIR=$(find "${SRCDIR}" -type f -name maubot.yaml | head -1)
    PLUGIN_DIR=$(dirname "${PLUGIN_DIR}")
    VERSION=$(cat "${PLUGIN_DIR}/maubot.yaml" | yq -r .version | head -1)
    PLUGIN_ID=$(cat "${PLUGIN_DIR}/maubot.yaml" | yq -r .id | head -1)
    cd "${PLUGIN_DIR}"
    mbc build --output "${PKGDIR}/usr/lib/maubot/plugins/${PLUGIN_ID}_${VERSION}.mbp"
    cp "${ROOT}/debian.control" "${PKGDIR}/DEBIAN/control"
    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 "${PLUGIN_DIR}/maubot.yaml" {} \;
}

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

function build_maubot_plugin() {
    export REPO="${1}"
    export BUILDDIR=${ROOT}/build
    export SRCDIR=${ROOT}/build/srcdir
    export PKGDIR=${ROOT}/build/pkgdir
    mkdir -p ${SRCDIR} ${PKGDIR}
    fetch
    prepare
    package
}