#!/bin/sh

set -eu

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

backend="$(dirname "$0")"
. "${backend}/environment.sh"

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

create_chroot() {
  echo "I: creating $debci_suite chroot (may take a while)"
  local chroot_path
  chroot_path="$1"

  http_proxy="${http_proxy:-}"
  if [ -z "$http_proxy" ]; then
    # detect a local apt-cacher-ng cache running.  10.0.2.2 = default IP
    # assigned to host system as seen from a kvm/virtualbox virtual machine
    for ip in 127.0.0.1 10.0.2.2; do
      if nc -z -w 1 $ip 3142; then
        export http_proxy=http://$ip:3142
      fi
    done
  fi

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

  # FIXME automate chroot creation for foreign architectures where a
  # qemu-user-static binary is needed
  debootstrap --include=dpkg-dev --arch="$debci_arch" "$debci_suite" "$chroot_path" ${debci_mirror}

  # use proxy
  if [ -n "$http_proxy" ]; then
    echo "Acquire::http::Proxy \"$http_proxy\";" > "${chroot_path}/etc/apt/apt.conf.d/01proxy"
  fi

  # do not download translations
  echo 'Acquire::Languages "none";' > "${chroot_path}/etc/apt/apt.conf.d/99translations"

  if grep -q debian "${chroot_path}/etc/apt/sources.list"; then
    debci-generate-apt-sources \
      --mirror="$debci_mirror" \
      --source \
      --buildd \
      --dbgsym \
      -- \
      "$debci_suite" \
      > "$chroot_path/etc/apt/sources.list"
  else
    sed -e 's/^deb\s/deb-src /' "${chroot_path}/etc/apt/sources.list" > "${chroot_path}/etc/apt/sources.list.d/sources.list"
  fi

  # never ask for input
  echo 'debconf debconf/frontend select noninteractive' | chroot "$chroot_path" debconf-set-selections

  # use unsafe I/O in dpkg to speed up the installation of packages
  echo 'force-unsafe-io' > "${chroot_path}/etc/dpkg/dpkg.cfg.d/debci"

  # create debci user inside the chroot, with the same UID as the debci user on
  # the host system
  chroot "$chroot_path" \
    useradd \
      --home-dir /home/debci \
      --create-home \
      --uid "$debci_uid" \
      debci

  chroot "$chroot_path" apt-get update
}

setup_schroot() {
  local chroot_path
  chroot_path="$1"

  local data_dir=$(readlink -f ${debci_data_basedir})
  local user=$(stat -c %U "${data_dir}")
  if [ -z "$user" ]; then
    user=debci
  fi

  union_type=''
  if grep -q '^nodev\s*aufs$' /proc/filesystems; then
    union_type=aufs
  fi
  if grep -q '^nodev\s*overlay$' /proc/filesystems; then
    union_type=overlay
  fi
  if [ -z "$union_type" ]; then
    echo "E: can't find an usable union mount filesystem (tried: overlay, aufs)"
    exit 1
  fi

  cat > /etc/schroot/chroot.d/"${debci_chroot_name}" <<EOF
[$debci_chroot_name]
type=directory
profile=debci
description=debci $debci_suite/$debci_arch chroot
directory=${chroot_path}
users=$user
groups=$user
root-users=$user
source-root-users=$user
root-groups=root
union-type=$union_type
EOF

  if [ ! -e /etc/schroot/debci ]; then
    ln -s "$debci_base_dir/etc/schroot/debci" /etc/schroot/debci
  fi
}

setup_suite() {
  # create chroot directory
  if [ ! -d "${debci_chroots_dir}" ]; then
    mkdir "${debci_chroots_dir}"
  fi

  local existing
  existing=$(schroot --config --chroot "$debci_chroot_name" | grep '^directory=' | cut -d = -f 2)

  path="$(mktemp --directory --tmpdir=${debci_chroots_dir} ${debci_chroot_name}.XXXXXXXXXX)"
  create_chroot "$path"
  setup_schroot "$path"

  if [ -n "$existing" ]; then
    rm -rf "$existing"
  fi
}

if ! which schroot >/dev/null; then
  echo "E: schroot not installed"
  exit 1
fi

setup_suite
