#!/bin/bash
set -euo pipefail

# will be templated by nginx
# shellcheck disable=SC2140
eportal_url=${EPORTAL_URL:-"<!--# echo var="orig_scheme" -->://<!--# echo var="http_host" -->"}

if [ -e /etc/yum.repos.d/kernelcare.repo ]; then
    sed -Ei /etc/yum.repos.d/kernelcare.repo \
        -e "s,(baseurl|gpgkey)=https?://.+/kernelcare/,\1=$eportal_url/repo/kernelcare/,"
fi

if [ -e /etc/apt/sources.list.d/kcare.list ]; then
    # examples of repo urls replacements, urls without sig suffix (old format):
    # https://repo.cloudlinux.com/kernelcare/kernelcare-debian/8 -> /repo/kernelcare/kernelcare-debian/8
    # https://repo.cloudlinux.com/kernelcare-debian/8 -> /repo/kernelcare/kernelcare-debian/8 kcare main
    # https://repo.cloudlinux.com/kernelcare-ubuntu/20.04 -> /repo/kernelcare-ubuntu/20.04

    # examples of repo urls replacements, urls with sig suffix (new format):
    # https://repo.cloudlinux.com/kernelcare/ubuntu-sig202505/20.04 -> /repo/kernelcare/ubuntu-sig202505/20.04
    # https://repo.cloudlinux.com/kernelcare/debian-sig202505/12 -> /repo/kernelcare/debian-sig202505/12
    sed -Ei /etc/apt/sources.list.d/kcare.list \
        -e "s|https?://.+/kernelcare-debian/|$eportal_url/repo/kernelcare/kernelcare-debian/|" \
        -e "s|https?://.+/kernelcare-ubuntu/|$eportal_url/repo/kernelcare-ubuntu/|" \
        -e "s|https?://.+/(kernelcare/[a-zA-Z0-9]+[_-]sig[0-9]+)/|$eportal_url/repo/\1/|"
fi
