#! /bin/bash

# Thomas Lange, lange@informatik.uni-koeln.de, (c) 2001-2019

# --nocleanup
#debug="$@"

logf=$(mktemp)
error=0; trap 'rm -f $logf error=$(($?>$error?$?:$error))' ERR EXIT # save maximum error code

destdir=/files/scratch/debmirror
defmirror=debian.netcologne.de
arch=amd64
dist=bookworm,bookworm-updates,bookworm-backports,trixie,trixie-updates,trixie-backports

sect="--section main,contrib,non-free,non-free-firmware"
allopt="$@ --state-cache-days=100 --ignore-missing-release --ignore-release-gpg --passive --nosource --arch=$arch --i18n"

while getopts Dkv opt ; do
    case "$opt" in
	k) mylocalmirror=1 ;;
	D) debian=1 # set mirror to an official Debian mirror
	   defmirror=deb.debian.org ;;
	v) xopt="-v";logf=/dev/stdout
    esac
done
shift $(($OPTIND - 1))


# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
update_from() {

    # update local mirror from a host
    host=$1
    shift
    defopt="--rsync-extra=none --diff=none $allopt --host=$host --dist=$dist $sect"

    echo "------------------ create mirror for debian ------------------" &>> $logf
    debmirror $excl $destdir/debian $defopt $xopt $* &>> $logf
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# main program
#

# excluding dbg_ packages saves a lot of disk space. About 33G for squeeze,wheezy in amd64,i386
excl="--exclude=-dbg_ --exclude=debian-installer-netboot-images --include=libc6-dbg"

# first sync from a mirror near to you
if [ -n "$mylocalmirror" ]; then

    update_from mylocalmirror --getcontents --method=http

    echo "------------------ create mirror for debian-security ------------------" &>> $logf
    debmirror --rsync-extra=none $excl $destdir/debian-security $allopt $xopt --method=http --host=mylocalmirror -r debian-security $sect -d buster/updates,bullseye-security/updates &>> $logf
fi

update_from $defmirror --getcontents  --method=http

# even one should not mirror the security site, but I will do it.
echo "------------------ create mirror for debian-security ------------------" &>> $logf

if [ -n "$debian" ]; then
    shost=security.debian.org
else
    shost=$defmirror
fi
debmirror --arch=$arch --rsync-extra=none $excl $destdir/debian-security $allopt $xopt --method=http --host=$shost -r debian-security $sect -d buster/updates,bullseye-security &>> $logf

if [ $error -ne 0 ]; then
    echo "mk-mirror ERROR found"
    cat $logf
fi
if [ "$xopt" != '-v' ]; then
    rm -f $logf
fi
