#!/bin/sh

ALT_NODEJS_REPO_PATH="/etc/apt/sources.list.d/alt-nodejs-els.list"
ALT_NODEJS_ROLLOUT_REPO_PATH="/etc/apt/sources.list.d/alt-nodejs-els-rollout.list"
ROLLOUT_SLOTS="1 2 3 4 5 6"

create_alt_nodejs_repo() {
    OS_CODENAME=$(grep '^VERSION_CODENAME=' /etc/os-release | cut -d'=' -f2 | sed -e 's@"@@g')
    OS_VER=$(grep '^VERSION_ID=' /etc/os-release | cut -d'=' -f2 | sed -e 's@"@@g')
    OS_NAME=$(grep '^ID=' /etc/os-release | cut -d'=' -f2 | sed -e 's@"@@g')

    mkdir -p "$(dirname "$ALT_NODEJS_REPO_PATH")"

    cat <<EOF > "$ALT_NODEJS_REPO_PATH"
### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# You may comment out this entry, but any other modifications may be lost.
deb [arch=amd64] https://repo.alt.tuxcare.com/alt-nodejs-els/deb/${OS_NAME}/${OS_VER}/stable ${OS_CODENAME} main
EOF

    chmod 644 "$ALT_NODEJS_REPO_PATH"
}

# Gradual-rollout slots els-alt-1..6, mirroring the rpm rollout repos (ELS-2641).
# Layout from build-system-configs/repositories/slots/els_alt_nodejs.json: the
# rollout host carries no channel segment (unlike the stable URL above) and
# takes no credentials, so no /etc/apt/auth.conf.d entry is needed.
# All six slot lines are active: the host serves only the slot this client is
# assigned to. The slot-N-bypass entries are the opt-in immediate update --
# uncomment one, then run apt update.
create_alt_nodejs_rollout_repo() {
    OS_CODENAME=$(grep '^VERSION_CODENAME=' /etc/os-release | cut -d'=' -f2 | sed -e 's@"@@g')
    OS_VER=$(grep '^VERSION_ID=' /etc/os-release | cut -d'=' -f2 | sed -e 's@"@@g')
    OS_NAME=$(grep '^ID=' /etc/os-release | cut -d'=' -f2 | sed -e 's@"@@g')
    # Derived rather than hardcoded amd64 as above, so arm64 hosts get a usable
    # rollout entry.
    ARCH=$(dpkg --print-architecture)

    mkdir -p "$(dirname "$ALT_NODEJS_ROLLOUT_REPO_PATH")"

    {
        echo "### THIS FILE IS AUTOMATICALLY CONFIGURED ###"
        echo "# You may comment out these entries, but any other modifications may be lost."
        for slot in $ROLLOUT_SLOTS; do
            echo "deb [arch=${ARCH}] https://rollout.alt.tuxcare.com/alt-nodejs-els/slot-${slot}/deb/${OS_NAME}/${OS_VER} ${OS_CODENAME} main"
        done
        echo "# Immediate update, bypassing the gradual rollout: uncomment one line below."
        for slot in $ROLLOUT_SLOTS; do
            echo "# deb [arch=${ARCH}] https://rollout.alt.tuxcare.com/alt-nodejs-els/slot-${slot}-bypass/deb/${OS_NAME}/${OS_VER} ${OS_CODENAME} main"
        done
    } > "$ALT_NODEJS_ROLLOUT_REPO_PATH"

    chmod 644 "$ALT_NODEJS_ROLLOUT_REPO_PATH"
}

create_alt_nodejs_repo
create_alt_nodejs_rollout_repo