#!/bin/sh

set -eu

base=$(readlink -f "$(dirname "$(readlink -f "$0")")/../..")
. "$base/lib/environment.sh"

if [ "$(whoami)" != root ]; then
  echo "E: This script must be run as root"
  exit 1
fi

# fail right away if lxc is not installed
if ! which lxc-create >/dev/null; then
  echo "E: lxc is not installed"
  exit 1
fi

# determine whether it's Debian or Ubuntu
script="/usr/share/debootstrap/scripts/${debci_suite:?}"
if [ -r "$script" ]; then
  if grep -q ubuntu.com "$script"; then
    distro=ubuntu
  elif grep -q kali.org "$script"; then
    distro=kali
  else
    distro=debian
  fi
else
  echo "ERROR: $script does not exist; debootstrap is not installed, or $debci_suite is an unknown suite" >&2
  exit 1
fi

script=$(mktemp --tmpdir debci-lxc-customize.XXXXXXXXXXX.sh)
if [ "$distro" = debian ]; then
  {
    echo "cat > /etc/apt/sources.list <<EOF"
    debci-generate-apt-sources \
      --source \
      --dbgsym \
      -- \
      "$debci_suite"
    echo "EOF"
    echo "while ! apt-get update; do sleep 10; done"
  } >> "$script"
fi
# configure guest proxy
if [ -n "${GUEST_PROXY:-}" ]; then
  echo "echo \"Acquire::http::Proxy \\\"$GUEST_PROXY\\\" ;\" > /etc/apt/apt.conf.d/70proxy" >> "$script"
fi
cat >> "$script" <<EOF
DEBIAN_FRONTEND=noninteractive \
  apt-get install dpkg-dev ca-certificates auto-apt-proxy -q -y --no-install-recommends

DEBIAN_FRONTEND=noninteractive \
  apt-get clean

useradd \
  --home-dir /home/debci \
  --create-home \
  debci
EOF

autopkgtest-build-lxc "$distro" "$debci_suite" "${debci_arch:?}" "$script"
