#!/bin/sh

AUTH_CONF_PATH="/etc/apt/auth.conf.d/php-els.conf"
PHP_REPO_PATH="/etc/apt/sources.list.d/php-els.list"
PHP_ROLLOUT_REPO_PATH="/etc/apt/sources.list.d/php-els-rollout.list"
ROLLOUT_SLOTS="1 2 3 4 5 6"

migrate_from_cloudlinux_to_tuxcare() {
    if [ -f "$AUTH_CONF_PATH" ]; then
        sed -i 's|repo.cloudlinux.com/php-els|repo.alt.tuxcare.com/alt-php-els|g' "$AUTH_CONF_PATH"
    fi
}

create_php_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')
    ARCH=$(dpkg --print-architecture)

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

# Gradual-rollout slots els-alt-1..6, mirroring the rpm rollout repos (ELS-2641).
# Layout from build-system-configs/repositories/slots/els_alt_php.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_php_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')
    ARCH=$(dpkg --print-architecture)

    mkdir -p "$(dirname "$PHP_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-php-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-php-els/slot-${slot}-bypass/deb/${OS_NAME}/${OS_VER} ${OS_CODENAME} main"
        done
    } > "$PHP_ROLLOUT_REPO_PATH"

    chmod 644 "$PHP_ROLLOUT_REPO_PATH"
}

create_php_repo
create_php_rollout_repo
migrate_from_cloudlinux_to_tuxcare
