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

completed=no

container_exists() {
  lxc-ls -f | awk "BEGIN { rc = 1 } { if (\$1 == \"$1\") { rc = 0 } } END { exit rc }"
}

container_running() {
  lxc-ls -f | awk "BEGIN { rc = 1 } { if (\$1 == \"$1\" && \$2 == \"RUNNING\") { rc = 0 } } END { exit rc }"
}

cleanup_container() {
  local c
  c="$1"
  if container_exists "$c"; then
    # is container $c running?
    if container_running "$c"; then
      lxc-stop --name="$c"
    fi
    lxc-destroy --name="$c"
  fi
}

cleanup() {
  if [ "$completed" = yes ]; then return; fi

  # autopkgtest-build-lxc can leave this behind in some cases
  cleanup_container "${container}.new"

  if [ "$created" = yes ]; then
    # autopkgtest-build-lxc succeeded, but our customization didn't. we can't
    # use the container in such state
    cleanup_container "$container"
  fi
}

trap cleanup EXIT

created=no
autopkgtest-build-lxc $distro $debci_suite $debci_arch
created=yes

LXC_PATH=$(lxc-config lxc.lxcpath) || LXC_PATH=/var/lib/lxc

rootfs=$LXC_PATH/$container/rootfs
# FIXME duplicates logic in bin/debci-setup-chdist && backends/schroot/create-testbed
if [ "$distro" = debian ]; then
  if [ "$debci_suite" = unstable ]; then
    buildd_suite="buildd-$debci_suite"
  elif [ "$debci_suite" = stable ]; then
    # workaround for bug #880105
    stable=$(curl -Ls http://deb.debian.org/debian/dists/stable/Release | grep-dctrl -n -s Codename '')
    buildd_suite="buildd-$stable-proposed-updates"
  else
    buildd_suite="buildd-$debci_suite-proposed-updates"
  fi
  cat > "${rootfs}/etc/apt/sources.list.d/buildd.list" <<EOF
deb http://incoming.debian.org/debian-buildd $buildd_suite main contrib main
deb-src http://incoming.debian.org/debian-buildd $buildd_suite main contrib main
EOF
  cat > "${rootfs}/etc/apt/sources.list.d/debug.list" <<EOF
deb http://deb.debian.org/debian-debug ${debci_suite}-debug main contrib main
deb-src http://deb.debian.org/debian-debug ${debci_suite}-debug main contrib main
EOF
  while ! chroot "$rootfs" apt-get update; do
    echo "I: apt-get update failed, let's wait some time and try again "
    sleep 10
  done
fi

# configure guest proxy
if [ -n "$GUEST_PROXY" ]; then
  echo "Acquire::http::Proxy \"$GUEST_PROXY\" ;" > "$rootfs/etc/apt/apt.conf.d/70proxy"
fi

DEBIAN_FRONTEND=noninteractive \
  chroot "$rootfs"  \
  apt-get install dpkg-dev -q -y --no-install-recommends

DEBIAN_FRONTEND=noninteractive \
  chroot "$rootfs"  \
  apt-get clean

chroot "$rootfs"  \
  useradd \
    --home-dir /home/debci \
    --create-home \
    debci

completed=yes
