#!/bin/sh
set -eu

usage() {
  cat <<EOF
usage: $0 [OPTIONS]

$@
EOF
}

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

root="$debci_data_basedir/chdist"
name="${debci_suite}-${debci_arch}"

# create new chdist if it doesn't exist already
if [ ! -e "$root/$name" ]; then
  echo "Creating new chdist $root/$name"
  chdist --data-dir "$root" create "$name" >/dev/null

  # figure out default mirror from debootstrap scripts
  DEF_MIRROR="http://ftp.debian.org/debian"
  SUITE=$debci_suite
  TARGET="$root/$name"
  ARCH=$debci_arch
  set +u
  . /usr/share/debootstrap/functions
  exec 4>&1
  # this updates $DEF_MIRROR (Ubuntu, ports, ..)
  . /usr/share/debootstrap/scripts/$debci_suite
  set -u

  # enable all components
  if [ "${DEF_MIRROR%ubuntu*}" = "$DEF_MIRROR" ]; then
    COMPONENTS="main"  # Debian
  else
    COMPONENTS="main restricted universe multiverse"  # Ubuntu
  fi

  mirror=${debci_mirror:-$DEF_MIRROR}

  # write apt sources.list
  mkdir -p $TARGET/etc/apt/
  echo "deb $mirror $SUITE $COMPONENTS
deb-src $mirror $SUITE $COMPONENTS" > "$TARGET/etc/apt/sources.list"

  # use a local proxy if available
  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 [ -n "$http_proxy" ]; then
    echo "Acquire::http::Proxy \"$http_proxy\";" > "$TARGET/etc/apt/apt.conf.d/01proxy"
  fi

  # disable multi-arch
  echo "Apt::Architectures {\"$ARCH\";};" > "$TARGET/etc/apt/apt.conf.d/97_no_multiarch"

  # disable unnecessary srcpkgcache
  echo 'Dir::Cache::srcpkgcache "";' > "$TARGET/etc/apt/apt.conf.d/98disable_cache"

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

# update apt indexes
chdist --data-dir "$root" apt-get "$name" update
