#! /bin/sh

set -e

. ${srcdir}/test.lib.sh

tl_plan 8

install -d debian/tmp
pkgdir=$(mktemp -d --tmpdir=debian pkg-dh-exec-XXXXXX)
pkgfile="${pkgdir}.install"

install -d "${pkgdir}/var/lib/dh-exec"
install -d "${pkgdir}/usr/lib/dh-exec/$(dpkg-architecture -qDEB_HOST_MULTIARCH)"

cat >${pkgfile} <<EOF
#! ${DH_EXEC_BINDIR}/dh-exec
${pkgfile} /var/lib/dh-exec/
${pkgfile} => /var/lib/dh-exec/new-file
${pkgfile} /usr/lib/dh-exec/\${DEB_HOST_MULTIARCH}/
${pkgfile} => /usr/lib/dh-exec/\${DEB_HOST_MULTIARCH}/new-file
EOF

chmod +x ${pkgfile}
${pkgfile} >${pkgfile}.output
dtmpdir=$(sed -n 's#\(debian/tmp/dh-exec\.[^/]*\).*#\1#gp' "${pkgfile}.output")

# Check that ${src} ${dest}/ gets passed through
cat ${pkgfile}.output | tl_expect "Copying to dir gets passed on, no expansions" \
        "${pkgfile} /var/lib/dh-exec/"
tl_next

# Check that ${src} ${dest}/new-file gets acted on
find ${dtmpdir}/var/lib/dh-exec/new-file -type f | \
        tl_expect "Copying a file with a rename gets acted upon" \
        "${dtmpdir}/var/lib/dh-exec/new-file"
tl_next

# Check that multiarch gets expanded
cat ${pkgfile}.output | \
        tl_expect "Multi-arch variable gets expanded, and copied" \
        "${pkgfile} /usr/lib/dh-exec/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/"
tl_next

# Check that multiarch gets expanded before copying
find ${dtmpdir}/usr/lib/dh-exec/ -type f -name 'new-file' | \
        tl_expect "Copying a file with a rename gets acted upon" \
        "${dtmpdir}/usr/lib/dh-exec/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/new-file"
tl_next

# Check that --without works
cat >${pkgfile} <<EOF
#! ${DH_EXEC_BINDIR}/dh-exec --without=subst
${pkgfile} /usr/lib/dh-exec/\${DEB_HOST_MULTIARCH}
EOF

chmod +x ${pkgfile}
${pkgfile} >${pkgfile}.output

cat ${pkgfile}.output | \
        tl_expect_match "dh_exec --without works" \
        "\${DEB_HOST_MULTIARCH}"

tl_next

# Check that --with works too
cat >${pkgfile} <<EOF
#! ${DH_EXEC_BINDIR}/dh-exec --with=install
${pkgfile} /usr/lib/dh-exec/\${DEB_HOST_MULTIARCH}
EOF

chmod +x ${pkgfile}
${pkgfile} >${pkgfile}.output

cat ${pkgfile}.output | \
        tl_expect_match "dh_exec --with works" \
        "\${DEB_HOST_MULTIARCH}"

tl_next

# Check that an empty list works too
cat >${pkgfile} <<EOF
#! ${DH_EXEC_BINDIR}/dh-exec --without=subst,install
${pkgfile} /usr/lib/dh-exec/\${DEB_HOST_MULTIARCH}
EOF

chmod +x ${pkgfile}
${pkgfile} >${pkgfile}.output

cat ${pkgfile}.output | \
        tl_expect_match "dh_exec --with works" \
        "\${DEB_HOST_MULTIARCH}"

tl_next

# Check that a program list works
cat >${pkgfile} <<EOF
#! ${DH_EXEC_BINDIR}/dh-exec --with=subst,install
${pkgfile} /usr/lib/dh-exec/\${DEB_HOST_MULTIARCH}
EOF

chmod +x ${pkgfile}
${pkgfile} >${pkgfile}.output

cat ${pkgfile}.output | \
        tl_expect_match "dh_exec --with works" \
        "$(dpkg-architecture -qDEB_HOST_MULTIARCH)"

tl_next

rm -rf debian
