#!/bin/sh
# ELS-2641: deliver the gradual-rollout list to hosts installed before ELS-2641
# shipped. apk runs nothing on upgrade, so post-install alone never reaches them.
#
# This must NOT be a plain copy of post-install. The stable list holds a
# per-server token that install-els-alt-python-apk-repo.sh substitutes in place of
# the literal $TOKEN placeholder at registration time. Rewriting that file
# verbatim on every upgrade would reset a registered host back to $TOKEN and
# break its stable repo with HTTP 401 until the installer was re-run with
# --force. So carry any already-substituted token across, using the same
# extraction the installer itself uses, and only fall back to the placeholder
# when there is nothing to preserve.
#
# The rollout list carries no token and is rewritten, which refreshes the Alpine
# version in the URLs. That does reset an uncommented slot-N-bypass line, which
# is intended: the bypass is a one-shot "update me now" opt-in, not durable
# state.

ALPINE_VER=$(cat /etc/alpine-release 2>/dev/null | cut -d. -f1,2)
STABLE_LIST=/etc/apk/repositories.d/alt-python-els.list
ROLLOUT_LIST=/etc/apk/repositories.d/alt-python-els-rollout.list

mkdir -p /etc/apk/repositories.d

token='$TOKEN'
if [ -f "$STABLE_LIST" ]; then
    existing=$(sed -n 's|.*/alt-python-els/\([^/]*\)/apk/.*|\1|p' "$STABLE_LIST" | head -n1)
    if [ -n "$existing" ]; then
        token="$existing"
    fi
fi

cat > "$STABLE_LIST" <<EOF
https://repo.alt.tuxcare.com/alt-python-els/${token}/apk/alpine/${ALPINE_VER}/stable
EOF

cat > "$ROLLOUT_LIST" <<EOF
https://rollout.alt.tuxcare.com/alt-python-els/slot-1/apk/alpine/${ALPINE_VER}
https://rollout.alt.tuxcare.com/alt-python-els/slot-2/apk/alpine/${ALPINE_VER}
https://rollout.alt.tuxcare.com/alt-python-els/slot-3/apk/alpine/${ALPINE_VER}
https://rollout.alt.tuxcare.com/alt-python-els/slot-4/apk/alpine/${ALPINE_VER}
https://rollout.alt.tuxcare.com/alt-python-els/slot-5/apk/alpine/${ALPINE_VER}
https://rollout.alt.tuxcare.com/alt-python-els/slot-6/apk/alpine/${ALPINE_VER}
# Immediate update, bypassing the gradual rollout: uncomment one line below.
# https://rollout.alt.tuxcare.com/alt-python-els/slot-1-bypass/apk/alpine/${ALPINE_VER}
# https://rollout.alt.tuxcare.com/alt-python-els/slot-2-bypass/apk/alpine/${ALPINE_VER}
# https://rollout.alt.tuxcare.com/alt-python-els/slot-3-bypass/apk/alpine/${ALPINE_VER}
# https://rollout.alt.tuxcare.com/alt-python-els/slot-4-bypass/apk/alpine/${ALPINE_VER}
# https://rollout.alt.tuxcare.com/alt-python-els/slot-5-bypass/apk/alpine/${ALPINE_VER}
# https://rollout.alt.tuxcare.com/alt-python-els/slot-6-bypass/apk/alpine/${ALPINE_VER}
EOF

exit 0
