#!/bin/sh

export DIST=1.7_x86-64
export NDK_DIR=/opt/build-environments/astralinux-1.7
export BASE_URL=https://download.astralinux.ru/astra/stable/1.7_x86-64

export INST_REPO_URL="${BASE_URL}/repository-main"

export APT_SOURCES_FULL="
# repository-extended contains additional components: astra-ce backports experimental gitlab
deb [trusted=yes] ${BASE_URL}/repository-base ${DIST} main contrib non-free
deb [trusted=yes] ${BASE_URL}/repository-extended ${DIST} main contrib non-free
"

export COMPONENTS="main,contrib,non-free"

# ==============================================================================

set -e
set -x

sudo apt install debootstrap -yyy

sudo mkdir -p "${NDK_DIR}"
sudo debootstrap --components="${COMPONENTS}" "${DIST}" "${NDK_DIR}" "${INST_REPO_URL}"

echo "${APT_SOURCES_FULL}" | sudo tee "${NDK_DIR}/etc/apt/sources.list"

echo "export LC_ALL=C" | sudo tee -a "${NDK_DIR}/root/.bashrc"
echo "export DEB_BUILD_OPTIONS=\"ccache nocheck parallel=$(nproc)\"" | sudo tee -a "${NDK_DIR}/root/.bashrc"
echo "export DEBUILD_PREPEND_PATH=\"/usr/lib/ccache\"" | sudo tee -a "${NDK_DIR}/root/.bashrc"
echo "[ -f /usr/share/bash-completion/bash_completion ] && . /usr/share/bash-completion/bash_completion" | sudo tee -a "${NDK_DIR}/root/.bashrc"

echo "mk-build-deps -ir" | sudo tee -a "${NDK_DIR}/root/.bash_history"
echo "fakeroot ./debian/rules binary" | sudo tee -a "${NDK_DIR}/root/.bash_history"
echo "debuild -d -- clean" | sudo tee -a "${NDK_DIR}/root/.bash_history"
echo "apt purge '*build-deps*'" | sudo tee -a "${NDK_DIR}/root/.bash_history"
echo "apt autoremove --purge" | sudo tee -a "${NDK_DIR}/root/.bash_history"

sudo mount -t proc proc ${NDK_DIR}/proc/
sudo mount -o bind /sys/ ${NDK_DIR}/sys/
sudo mount -o bind /dev/ ${NDK_DIR}/dev/
sudo mount -o bind /dev/pts ${NDK_DIR}/dev/pts

sudo mount --make-rslave ${NDK_DIR}/sys
sudo mount --make-rslave ${NDK_DIR}/dev
sudo mount --make-rslave ${NDK_DIR}/dev/pts

sudo chroot ${NDK_DIR} apt update
sudo chroot ${NDK_DIR} apt install devscripts quilt equivs ccache bash-completion sudo -yyy
sudo chroot ${NDK_DIR} apt clean

sudo chown -R "${USER}:${USER}" ${NDK_DIR}/opt/

set +x

echo
echo "Build environment is ready for usage!"
echo "sudo chroot \"${NDK_DIR}\""

