#
# Test that a pkgsrc package can be built.  This takes the package
# path as an argument, and can be run like this:
#
#   bracket run-external-test current pkgsrc editors/emacs
#
# This works with noemu, and now also with qemu provided the VM
# has enough disk space, which it doesn't by default.
# A multiprocessor system is preferred as building pkgsrc on
# a uniprocessor is painfully slow.
#
# Logs are redirected to files because otherwise performance is
# limited by the serial console when using noemu.
#
# This downloads pkgsrc as a tar file and then updates it from CVS,
# which is faster than checking it out from CVS as in
# https://www.netbsd.org/docs/pkgsrc/getting.html#getting-via-cvs:
# cvs -q -z2 -d anoncvs@anoncvs.NetBSD.org:/cvsroot checkout -P pkgsrc >cvs-update.log 2>&1

from __future__ import print_function

from bracket import *

pkgsrc_tgz_url = 'ftp://ftp.NetBSD.org/pub/pkgsrc/current/pkgsrc.tar.gz'

# Construct a test predicate function for building the package
# "pkgpath" (e.g., "editors/emacs")

def make_test_func(pkgpath, name):
    def test_func(ts):
        logfn = os.path.join(results_dir(ts), name + ".log")
        return anita_run_1(ts, "boot",
                logfn,
                extra_anita_args = [
                    "--run",
                        "set -x; " + \
                        "netstat -rn -f inet | grep default || dhcpcd -w; " + \
                        "cd /usr && ftp -o pkgsrc.tar.gz %s && " % pkgsrc_tgz_url + \
                        "tar -xzf pkgsrc.tar.gz && " + \
                        "cd pkgsrc && cvs -q update -dP && cd .. && " + \
                        "echo \"MAKE_JOBS=$(sysctl -n hw.ncpuonline)\" >>/etc/mk.conf && " + \
                        "cd pkgsrc/%s && " % pkgpath + \
                            "make install >make.log 2>&1; status=$?; tail -n 200 make.log; test $status = 0",
                    "--run-timeout", "86400",
                    "--no-install"
                ])
    return test_func

def op(pkgpath):
    pkgcategory, pkgname = pkgpath.split('/')
    name = 'pkgsrc_' + pkgname
    return TestOp(make_test_func(pkgpath, name), [install_op], name = name)
