#!/bin/bash

set -exo pipefail

. ../.skel/helpers.sh

PKGNAME=ansible-semaphore

API_URL=https://api.github.com/repos/semaphoreui/semaphore/releases
JQ_EXPR='.[] | select( .prerelease==false and .draft==false and (.tag_name|test("^v[0-9.-]+$")) ) | "\(.name[1:]) \(.published_at) \(.assets[] | select(.name|test(".*_linux_amd64.tar.gz$")).browser_download_url )"'

ROOT=$(pwd)
function fetch() {
    cd "${SRCDIR}"
    wget "${URL}" --output-document "semaphore_${VERSION}_linux_amd64.tar.gz"
    tar xf "semaphore_${VERSION}_linux_amd64.tar.gz"
}

function prepare() {
    chmod +x "${SRCDIR}/semaphore"
    mkdir -p \
          "${PKGDIR}/DEBIAN" \
          "${PKGDIR}/usr/bin" \
          "${PKGDIR}/etc/semaphore" \
          "${PKGDIR}/var/lib/semaphore/playbooks" \
          "${PKGDIR}/var/lib/semaphore/database" \
          "${PKGDIR}/lib/systemd/system" \
	  "${PKGDIR}/usr/share/doc/${PKGNAME}"
    cp "${SRCDIR}/semaphore" "${PKGDIR}/usr/bin/semaphore"
    cp "${ROOT}/semaphore.service" "${PKGDIR}/lib/systemd/system/semaphore.service"
    cp "${ROOT}/debian.control" "${PKGDIR}/DEBIAN/control"
    cp "${ROOT}/debian.conffiles" "${PKGDIR}/DEBIAN/conffiles"
    cp "${ROOT}/debian.postinst" "${PKGDIR}/DEBIAN/postinst"
    cp "${ROOT}/debian.prerm" "${PKGDIR}/DEBIAN/prerm"
    cp "${ROOT}/debian.postrm" "${PKGDIR}/DEBIAN/postrm"
    cp "${ROOT}/config.json" "${PKGDIR}/etc/semaphore/config.json"
    sed -re "s/__VERSION__/${VERSION}/g" -i "${PKGDIR}/DEBIAN/control"
    sed -re "s/__MAINTAINER__/${MAINTAINER}/g" -i "${PKGDIR}/DEBIAN/control"
    cp "${SRCDIR}/LICENSE" "${PKGDIR}/usr/share/doc/${PKGNAME}/copyright"
    github_changelog semaphoreui/semaphore
    find "${PKGDIR}" -exec touch -m -d "${ISODATE}" {} \;
}

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

function build() {
    read VERSION ISODATE URL <<<$(curl "${API_URL}" | jq -r "${JQ_EXPR}" | head -1)
    # Replace Forgejo patch level separater - with . to be Debian versioning compatible, and add epoch number 2
    export VERSION="${VERSION/-/.}"
    export ISODATE
    export URL
    export BUILDDIR=${ROOT}/build
    export SRCDIR=${ROOT}/build/srcdir
    export PKGDIR=${ROOT}/build/pkgdir
    mkdir -p ${SRCDIR} ${PKGDIR}
    fetch
    prepare
    package
}
 

build