#!/bin/sh

set -eu

if [ -z "$AUTOPKGTEST_NORMAL_USER" ]; then
    echo "No normal user available, test cannot be run"
    exit 77
fi

AUTOPKGTEST_NORMAL_UID="$(id -u "$AUTOPKGTEST_NORMAL_USER")"
AUTOPKGTEST_NORMAL_GID="$(id -g "$AUTOPKGTEST_NORMAL_USER")"

if ! grep -qx "$AUTOPKGTEST_NORMAL_UID:.*" /etc/subuid; then
    echo "Adding a subuid allocation for $AUTOPKGTEST_NORMAL_USER"
    echo "$AUTOPKGTEST_NORMAL_UID:1000000:65536" >> /etc/subuid
fi

if ! grep -qx "$AUTOPKGTEST_NORMAL_GID:.*" /etc/subgid; then
    echo "Adding a subgid allocation for $AUTOPKGTEST_NORMAL_USER's group"
    echo "$AUTOPKGTEST_NORMAL_GID:1000000:65536" >> /etc/subgid
fi

if ! unshare --user --map-auto --setuid 0 --setgid 0 --mount --pid --fork --mount-proc true; then
    echo "Unshare failed, bailing"
    exit 77
fi

. "$(dirname "$0")/common.sh"

echo running "$0"

test_this piuparts --version

cd "$AUTOPKGTEST_TMP"

create_packages

chown "$AUTOPKGTEST_NORMAL_USER:" t.deb f.deb

test_this runuser -u "$AUTOPKGTEST_NORMAL_USER" -- piuparts t.deb
