#!/bin/sh

ARCH=$(uname -m)
AUTH_CONF_PATH=/etc/apk/repositories.d/els-alpine-release.list

mkdir -p /etc/apk/repositories.d

# Carry an already-substituted repo token across the upgrade.
#
# install-els-alpine-repo.sh registers the host with CLN and then replaces the
# literal $TOKEN placeholder in this file with a per-server token:
#     sed -i "s/\$TOKEN/$token/g" /etc/apk/repositories.d/els-alpine-release.list
# Rewriting the file verbatim here reset every registered host back to $TOKEN,
# so its stable repo started returning HTTP 401 on each apk update until the
# installer was re-run with --force. Extract the existing token first, using the
# same expression the installer uses to read it back, and only fall back to the
# placeholder when there is nothing to preserve.
token='$TOKEN'
if [ -f "$AUTH_CONF_PATH" ]; then
    existing=$(sed -n 's|.*alpinelinux3.18-els/\([^/]*\)/stable.*|\1|p' "$AUTH_CONF_PATH" | head -n1)
    if [ -n "$existing" ] && [ "$existing" != '$TOKEN' ]; then
        token="$existing"
    fi
fi

cat > "$AUTH_CONF_PATH" <<EOF
https://repo.tuxcare.com/alpinelinux3.18-els/${token}/stable
EOF

# Provide ELS marker file needed for OVAL tests (same as els-define on other distros)
NAME="Alpine Linux"
VERSION_ID="3.18"
if [ -r /etc/os-release ]; then
    . /etc/os-release
fi
# OVAL tests expect major.minor only ("3.18"), while /etc/os-release
# carries the full patch version (VERSION_ID=3.18.12) -- trim it.
VERSION_ID=$(printf '%s' "$VERSION_ID" | cut -d. -f1,2)
[ -n "$VERSION_ID" ] || VERSION_ID="3.18"
[ -n "$NAME" ] || NAME="Alpine Linux"
echo "${NAME} ${VERSION_ID} (ELS by TuxCare)" > /etc/els-release
chmod 0644 /etc/els-release

exit 0
