#!/bin/bash

set -exo pipefail


ROOT=$(pwd)
function fetch() {
    git clone https://gitlab.com/s3lph/prometheus2influxdb "${SRCDIR}"
    cd "${SRCDIR}"
    export VERSION=0.$(git rev-list --count HEAD)
}

function prepare() {
    chmod +x "${SRCDIR}/prometheus2influxdb.py"
    mkdir -p \
          "${PKGDIR}/DEBIAN" \
          "${PKGDIR}/usr/bin" \
          "${PKGDIR}/etc/default" \
          "${PKGDIR}/lib/systemd/system"
    cp "${SRCDIR}/prometheus2influxdb.py" "${PKGDIR}/usr/bin/prometheus2influxdb.py"
    cp "${SRCDIR}/config.yaml" "${PKGDIR}/etc/prometheus2influxdb.yaml"
    cp "${ROOT}/prometheus2influxdb.defaults" "${PKGDIR}/etc/default/prometheus2influxdb"
    cp "${ROOT}/prometheus2influxdb.service" "${PKGDIR}/lib/systemd/system/prometheus2influxdb.service"
    cp "${ROOT}/prometheus2influxdb.timer" "${PKGDIR}/lib/systemd/system/prometheus2influxdb.timer"
    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"
    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 -d "${ISODATE}" {} \;
}

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

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

build