#!/bin/sh

set -e

echo "warning: this script is now redundant. upstream Grml images ship with the stressant package."

if dpkg --compare-versions $(lsb_release -r -s) \>= 9.0; then
    echo "debian 9 (stretch) or later detected, using /usr/share/keyrings/grml-archive.gpg"
    keyring=/usr/share/keyrings/grml-archive.gpg
else
    echo "debian 8 (jessie) or earlier detected, using /etc/apt/trusted.gpg.d/grml-archive.gpg"
    keyring=/etc/apt/trusted.gpg.d/grml-archive.gpg
fi
# this is a shell version of the instructions proposed here:
# https://github.com/grml/grml.org/pull/13
if [ -e /etc/apt/sources.list.d/grml.list ]; then
    echo "grml sources.list already configured"
else
    echo "adding grml sources.list"
    if dpkg --compare-versions $(lsb_release -r -s) \>= 9.0; then
        cat > /etc/apt/sources.list.d/grml.list <<EOF
deb [signed-by=/usr/share/keyrings/grml-archive.gpg] https://deb.grml.org/ grml-testing main
EOF
    else
        cat > /etc/apt/sources.list.d/grml.list <<EOF
deb [signed-by=709BCE51568573EBC160E590F61E2E7CECDEA787] https://deb.grml.org/ grml-testing main
EOF
    fi
fi
if [ -e /etc/apt/preferences.d/grml.pref ]; then
    echo "grml prerefences pinning already configured"
else
    echo "adding grml preferences pinning"
    cat > /etc/apt/preferences.d/grml.pref <<EOF
Package: *
Pin: release a=grml-stable
Pin-Priority: 100

Package: *
Pin: release a=grml-testing
Pin-Priority: 100
EOF
fi

if [ -e "$keyring" ]; then
    echo "OpenPGP trust anchor already exists"
else
    echo "fetching OpePGP trust anchor"
    wget -O "$keyring" https://deb.grml.org/repo-key.gpg
fi
echo "refreshing sources"
apt-get update
echo "installing grml-live"
env DEBIAN_FRONTEND=noninteractive apt-get install -y grml-live
echo "adding custom stressant config"
printf "PACKAGES install\n\nstressant\n" >> /etc/grml/fai/config/package_config/STRESSANT

echo "building amd64 release"
grml-live -F -c DEBORPHAN,GRMLBASE,GRML_FULL,RELEASE,AMD64,IGNORE,STRESSANT -s unstable -a amd64 -o $PWD/grml64 -v $(date +%Y.%m) -r gossage -g grml64-full-stressant $GRML_LIVE_FLAGS

echo "building i386 release"
grml-live -F -c DEBORPHAN,GRMLBASE,GRML_FULL,RELEASE,I386,IGNORE,STRESSANT -s unstable -a i386 -o $PWD/grml32 -v $(date +%Y.%m) -r gossage -g grml32-full-stressant $GRML_LIVE_FLAGS

echo "merging the two ISOs"
mkdir -p grml96/grml_isos/
grml2iso -o grml96/grml_isos/grml96-full-stressant_$(date +%Y.%m).iso grml64/grml_isos/grml64-full-stressant_$(date +%Y.%m).iso grml32/grml_isos/grml32-full-stressant_$(date +%Y.%m).iso

echo "handy symlinks"
ln -sf grml64/grml_isos/grml64-full-stressant_$(date +%Y.%m).iso grml64-full-stressant.iso
ln -sf grml32/grml_isos/grml32-full-stressant_$(date +%Y.%m).iso grml32-full-stressant.iso
ln -sf grml96/grml_isos/grml96-full-stressant_$(date +%Y.%m).iso grml96-full-stressant.iso
