#!/bin/bash

set -o errexit
set -o nounset

source /etc/lsb-release

: "${MCC_CDN_DEBIAN:=${KAAS_CDN_BASE_URL}}"

function get_ubuntu_snapshot() {
  for name in $(curl -sL "${MCC_CDN_DEBIAN}/kaas/" \
      | grep -oP '(?<=\<a href\=\")ubuntu-.*(?=\/\">)' | sort -r); do
    url="${MCC_CDN_DEBIAN}/kaas/${name}/dists/${DISTRIB_CODENAME}"
    if curl --output /dev/null --silent --head --fail "${url}"; then
      echo "${name}"
      return
    fi
  done
}

name=$(get_ubuntu_snapshot)
if [[ -z ${name} ]]; then
  echo "No Ubuntu snapshot found!"
  exit 1
fi

repo_url="${MCC_CDN_DEBIAN}/kaas/${name}"
echo "Adding Ubuntu repository ${repo_url} ..."

cat << EOF | sudo tee /etc/apt/sources.list.d/airgapped.list
# Ubuntu snapshot
deb [arch=amd64] ${repo_url} ${DISTRIB_CODENAME} main restricted universe
deb [arch=amd64] ${repo_url} ${DISTRIB_CODENAME}-updates main restricted universe
deb [arch=amd64] ${repo_url} ${DISTRIB_CODENAME}-security main restricted universe
EOF

sudo apt update
