#! /bin/sh

set -ex

export DEB_BUILD_OPTIONS=""

do_build=
do_install=
stdout_dest="/dev/null"
args=$(getopt -o "vqs:" -l "verbose,quick,skip:,build,install" -- "$@")
eval set -- "$args"
while [ $# -gt 0 ]; do
    case $1 in
	-v|--verbose)
            stdout_dest="/dev/stdout"
	    ;;
	-q|--quick)
            DEB_BUILD_OPTIONS="$DEB_BUILD_OPTIONS nocheck"
	    ;;
        --build)
            do_build=t
            ;;
        --install)
            do_install=t
            ;;
	--)
	    shift
	    break
	    ;;
    esac
    shift
done
tar="$1"


# Build

if [ -n "$do_build" ]; then
    rm -rf build-results
    mkdir build-results
    resultdir=$PWD/build-results
    upstream_ver=$(ls cockpit-*.tar.gz | sed 's/^.*-//; s/.tar.gz//' | head -n1)

    ln -sf cockpit-*.tar.gz cockpit_${upstream_ver}.orig.tar.gz

    rm -rf cockpit-*/
    tar -xzf cockpit-*.tar.gz
    ( cd cockpit-*/
      cp -rp tools/debian debian
      # put proper version into changelog, as we have versioned dependencies
      sed -i "1 s/(.*)/($upstream_ver-1)/" debian/changelog
      # Hack: Remove PCP build dependencies while pcp is not in testing
      # (https://tracker.debian.org/pcp)
      sed -i '/libpcp.*-dev/d' debian/control
      dpkg-buildpackage -S -uc -us -nc
    )

    # Some unit tests want a real network interface
    echo USENETWORK=yes >>~/.pbuilderrc

    # pbuilder < 0.228.6 has broken /dev/pts/ptmx permissions; affects Ubuntu < 17.04
    # see https://bugs.debian.org/841935
    if ! grep -q ptmxmode /usr/lib/pbuilder/pbuilder-modules; then
        echo "Fixing /dev/pts/ptmx mode in pbuilder"
        sed -i '/mount -t devpts none/ s/$/,ptmxmode=666,newinstance/' /usr/lib/pbuilder/pbuilder-modules
    fi

    pbuilder build --buildresult "$resultdir" \
                   --logfile "$resultdir/build.log" \
                   cockpit_${upstream_ver}-1.dsc >$stdout_dest
    lintian $resultdir/cockpit_*_$(dpkg --print-architecture).changes >&2
fi

# Install

if [ -n "$do_install" ]; then
    packages=$(find build-results -name "*.deb")
    dpkg --install $packages

    # FIXME: our tests expect cockpit.socket to not be running after boot, only
    # after start_cockpit().
    systemctl disable cockpit.socket

    # firewall-cmd --add-service=cockpit --permanent

    rm -rf /var/log/journal/*
fi
