#!/bin/sh
# Common autopkgtest script for testing a dkms source package.
# Author: Martin Pitt <martin.pitt@ubuntu.com>
# Copyright: (C) 2014 Canonical Ltd.

# IOhannes m zmölnig
# - 2018-07-13: removed cruft, simplified and don't require apt install
set -eu

purge_adt_artifacts=no
if [ -z ${ADT_ARTIFACTS+x} ]; then
  ADT_ARTIFACTS=$(mktemp -d)
  echo "I: created temporaray ARTIFACTS directory ${AUTOPKGTEST_ARTIFACTS}"
  purge_adt_artifacts=yes
fi

run_pkg() {
    pkg="$1"

    if ! dkms_conf=$(dpkg -L $pkg | grep 'dkms.conf$'); then
        echo "I: Package $pkg has no dkms.conf, skipping"
        return
    fi

    # collect build logs as artifacts
    if [ -d /var/lib/dkms ]; then
        (cd /var/lib/dkms; find -name "make.log" -print0 | xargs -0 tar c | echo "") > "$AUTOPKGTEST_ARTIFACTS/$pkg-make-logs.tar"
    fi

    echo "I: Testing binary package $pkg"
    dkms_pkg=$(bash -c ". $dkms_conf; echo \$PACKAGE_NAME" 2>/dev/null)

    echo "I: Testing if $dkms_pkg modules are correctly installed"
    dkmsstatus="$(dkms status $dkms_pkg)"
    if [ -z "$dkmsstatus" ]; then
        echo "E: dkms status output is empty!" >&2
        exit 1
    fi
    echo "$dkmsstatus"

    if ! echo "$dkmsstatus" | grep -q "installed$"; then
        echo "E: not installed" >&2
        exit 1
    fi
}

pkgs="$@"
if [ x"${pkgs}" = "x" ]; then
  pkgs=$(awk '/^Package:.*/ { print $2 }' debian/control)
fi

for pkg in $pkgs; do
    # package might be arch: restriction or udeb etc.
    if ! dpkg-query -W "${pkg}" >/dev/null 2>&1; then
        echo "I: Skipping unavailable package $pkg"
        continue
    fi
    run_pkg $pkg
done

if [ "x${purge_adt_artifacts}" = "xyes" ]; then
  rm -rf "${AUTOPKGTEST_ARTIFACTS}"
fi

