#!/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

# detect a local apt-cacher-ng and use it in the container
http_proxy="${http_proxy:-}"
if [ -z "$http_proxy" ]; then
  if nc -z -w 1 127.0.0.1 3142; then
    # for debootstrap:
    export http_proxy=http://127.0.0.1:3142
  fi
fi

# also lookup up proxy in the apt configuration
if [ -z "$http_proxy" ]; then
  eval $(apt-config shell http_proxy Acquire::http::Proxy)
  if [ -n "$http_proxy" ]; then
    export http_proxy
  fi
fi

# guess apt proxy for the guest:
GUEST_PROXY=
if [ -n "$http_proxy" ]; then
  local_proxy=no
  case "$http_proxy" in
    http://127.0.0.1:*)
      local_proxy=yes
      ;;
    http://localhost:*)
      local_proxy=yes
      ;;
  esac

  if [ "$local_proxy" = yes ]; then
    # translate 127.0.0.1 to a valid address as seen from the guest
    bridge_interface=$(awk '{ if ($1 == "lxc.network.link" || $1 == "lxc.net.0.link") print($3)}' /etc/lxc/default.conf)
    if [ -n "$bridge_interface" ]; then
      bridge_ip=$(ip -4 a show dev "$bridge_interface" | awk '/ inet / {sub(/\/.*$/, "", $2); print $2}')
      export GUEST_PROXY=http://$bridge_ip:3142
    fi
  else
    export GUEST_PROXY=$http_proxy
  fi
fi

container=autopkgtest-${debci_suite}-${debci_arch}

script=$(mktemp --tmpdir debci-lxc-customize.XXXXXXXXXXX.sh)
if [ "$distro" = debian ]; then
  echo "cat > /etc/apt/sources.list <<EOF" >> "$script"
  debci-generate-apt-sources \
    --source \
    --buildd \
    --dbgsym \
    -- \
    "$debci_suite" \
    >> "$script"
  echo "EOF" >> "$script"
  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 -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
