#!/bin/sh

CWD="$PWD"
cd "$(dirname "$0")"

usage () {
    echo "$0 WORKDIR">&2
    exit 1
}

UPSTREAM_MIRROR_HOST=${UPSTREAM_MIRROR_HOST:-debian.inode.at}
UPSTREAM_MIRROR_METHOD=${UPSTREAM_MIRROR_METHOD:-http}
BASEDIR=/usr/share/debian-cd
WORKDIR="$1"; shift

mkdir -p "$WORKDIR"/mirror
mkdir -p "$WORKDIR"/localdebs
mkdir -p "$WORKDIR"/debian-cd-tmp

debmirror \
    -p \
    --host="$UPSTREAM_MIRROR_HOST" \
    --method="$UPSTREAM_MIRROR_METHOD" \
    --dist=stretch --section=main,main/debian-installer --arch=all,amd64\
    --di-dist=dists --di-arch=arches \
    --rsync-extra=doc,tools \
    --getcontents \
    --nosource \
    --check-gpg --keyring /usr/share/keyrings/debian-archive-keyring.gpg \
    "$WORKDIR"/mirror \
    || exit 1

cat > "$WORKDIR"/CONF.sh <<EOF
export BASEDIR=$BASEDIR

export CDNAME=grobian-server
export CODENAME=stretch
export DEBVERSION="9.1"
export VOLID_BASE="Grobian Server \$DEBVERSION"
export DI_CODENAME=\$CODENAME
export OFFICIAL="Unofficial"
export OFFICIAL_VAL=0

export ARCHES=amd64


export MIRROR="$WORKDIR"/mirror
export TDIR="$WORKDIR"/debian-cd-tmp
export OUT="$WORKDIR"/debian-cd-images
export APTTMP="$WORKDIR"/debian-cd-tmp/apt

export WGET=wget

export MAX_PKG_SIZE=600000000
export DISKTYPE=STICK4GB
export IMAGESUMS=1

export MAXJIGDOS=0
export MAXCDS=1
export MAXISOS=ALL

export SPLASHPNG="$PWD/data/softwaves.png"

# export TASK=Debian-mate # defaults to Debian-generic
export KERNEL_PARAMS="tasks=mate-desktop locale=en_GB.UTF-8 keymap=de language=en country=AT console-setup/variantcode=nodeadkeys"
export DESKTOP=mate

#export UDEB_INCLUDE="$BASEDIR"/data/\$CODENAME/udeb_include
#export UDEB_EXCLUDE="$BASEDIR"/data/\$CODENAME/udeb_exclude
#export BASE_INCLUDE="$BASEDIR"/data/\$CODENAME/base_include
#export BASE_EXCLUDE="$BASEDIR"/data/\$CODENAME/base_exclude

export LOCAL=1
export LOCALDEBS="$WORKDIR"/localdebs
EOF

#cat > "$WORKDIR"/base_include <<EOF
#EOF

CONFIG_DEBS_DIR=$(
    . "$WORKDIR"/CONF.sh
    DIR="$WORKDIR"/localdebs/dists/$CODENAME/local/binary-amd64
    rm -rf "$DIR"
    mkdir -p "$DIR"
    echo "$DIR"
)

dcmd cp -t "$CONFIG_DEBS_DIR" ../*.changes

(
    export CF="$WORKDIR"/CONF.sh
    . $CF
    cd "$BASEDIR"

    ./tools/Packages-gen $CODENAME amd64
    ./tools/Packages-gen -i $DI_CODENAME amd64

    make distclean ${CODENAME}_status ok init

    mkdir -p "$WORKDIR"/debian-cd-tmp/$CODENAME/tasks
    cat >> "$WORKDIR"/debian-cd-tmp/$CODENAME/tasks/forcd1 <<EOF
/* dxld config packages, I only build one CD might aswell put this here */
$(zcat $CONFIG_DEBS_DIR/Packages.*z* | sed -n  's/^Package: //p')
EOF

    make packagelists image-trees images
    #imagesums
)
