#!/bin/sh
set -e

file="$1"

# Trisquel: Deb822-first, keep legacy clean
: "${ROOT:=/target}"
SD="$ROOT/etc/apt/sources.list.d"
SF="$SD/trisquel.sources"
LEGACY="$ROOT/etc/apt/sources.list"
MSG="# Trisquel sources have moved to /etc/apt/sources.list.d/trisquel.sources"
mkdir -p "$SD"

FASTEST=https://archive.trisquel.org/trisquel/
SPEED=1000000000000

if nm-online -xq
then
    for i in $(grep '//' /usr/share/python-apt/templates/Trisquel.mirrors | sed 's|/$||')
    do
        echo Testing $i
        TIME=$(date +%s%N)
        wget --no-check-certificate -t 1 -T 5 --max-redirect=0 -o /dev/null -O /dev/null $i/speedtest || continue
        TIME2=$(date +%s%N)
        ELAPSED=$(expr $TIME2 - $TIME)
        echo Time: $ELAPSED
        if [ $ELAPSED -lt $SPEED ]
        then
            FASTEST=$i
            SPEED=$ELAPSED
        fi
    done
fi

echo "Selected mirror: $FASTEST"

MIRROR=$FASTEST
RELEASE=$(lsb_release -c | cut -f 2)

# Ensure MIRROR ends with a single trailing slash for Deb822 URIs
case "$MIRROR" in
  */) : ;;
  *) MIRROR="$MIRROR/";;
esac

# Use keyring in /usr/share/keyrings
SIGNED_BY="/usr/share/keyrings/trisquel-archive-keyring.gpg"

# Write Deb822 sources file in the requested structure
cat << EOF > "$SF"
# Trisquel repositories for supported software and updates
Types: deb
URIs: ${MIRROR}
Suites: ${RELEASE} ${RELEASE}-updates ${RELEASE}-security
Components: main
Signed-By: ${SIGNED_BY}

# Source package repositories
Types: deb-src
URIs: ${MIRROR}
Suites: ${RELEASE} ${RELEASE}-updates ${RELEASE}-security
Components: main
Signed-By: ${SIGNED_BY}

# Optional backports repository
Enabled: no
Types: deb deb-src
URIs: ${MIRROR}
Suites: ${RELEASE}-backports
Components: main
Signed-By: ${SIGNED_BY}
EOF

# Keep the legacy file and the pipeline temp file as a single breadcrumb line
printf '%s\n' "$MSG" > "$LEGACY"
printf '%s\n' "$MSG" > "$file"
exit 0
