#!/bin/sh
# Install a native package selected from /etc/os-release and CPU architecture.
set -eu
[ "$(id -u)" = 0 ] || { echo 'Execute como root.' >&2; exit 1; }
. /etc/os-release
case "$(uname -m)" in
    x86_64) debarch=amd64; rpmarch=x86_64 ;;
    aarch64|arm64) debarch=arm64; rpmarch=aarch64 ;;
    *) echo 'Arquitetura nao publicada.' >&2; exit 1 ;;
esac
case "$ID" in
    debian|ubuntu) distro=$ID; version=$VERSION_ID; manager=apt ;;
    almalinux|rocky|fedora|rhel|centos) distro=$ID; version=${VERSION_ID%%.*}; manager=dnf ;;
    opensuse-leap) distro=opensuse; version=$VERSION_ID; manager=zypper ;;
    *) echo "Distribuicao nao publicada: $ID $VERSION_ID" >&2; exit 1 ;;
esac
# The panel supplies both values; reject a wrong target before touching packages.
if [ "$#" != 0 ]; then
    [ "$#" = 2 ] && [ "$1" = "$distro" ] && [ "$2" = "$version" ] || {
        echo "Sistema detectado ($distro $version) difere da configuracao; instalacao bloqueada." >&2
        exit 1
    }
fi
base=https://deb.schip.com.br/agents/linux/current
fingerprint=E5D6D296F1DC1DC41FC854060BD84F82256E033E
temporary=$(mktemp -d)
trap 'rm -rf "$temporary"' EXIT HUP INT TERM
if [ "$distro:$version" = centos:8 ]; then
    mkdir "$temporary/native-repos"
    cp /etc/yum.repos.d/*.repo "$temporary/native-repos/"
    sed -i -e 's/^mirrorlist=/#mirrorlist=/' -e 's#^\#baseurl=http://mirror.centos.org/\$contentdir/\$stream/#baseurl=https://vault.centos.org/8-stream/#' "$temporary"/native-repos/CentOS-Stream-*.repo
    dnf() { command dnf --setopt="reposdir=$temporary/native-repos" "$@"; }
fi
apt_native() {
    if [ -f "$temporary/ubuntu-native.list" ]; then
        apt-get -o Dir::Etc::sourcelist="$temporary/ubuntu-native.list" -o Dir::Etc::sourceparts=- -o APT::Get::List-Cleanup=false "$@"
    else
        apt-get "$@"
    fi
}
if [ "$distro" = ubuntu ]; then
    case "$version" in 18.10|19.*|20.10|21.*|22.10|23.*|24.10)
        codename=${VERSION_CODENAME:-${UBUNTU_CODENAME:-}}
        case "$codename" in ''|*[!a-z]*) echo 'Codename Ubuntu invalido' >&2; exit 1 ;; esac
        printf 'deb http://old-releases.ubuntu.com/ubuntu %s main universe restricted multiverse\ndeb http://old-releases.ubuntu.com/ubuntu %s-updates main universe restricted multiverse\n' "$codename" "$codename" > "$temporary/ubuntu-native.list"
        ;;
    esac
fi
if [ "$manager" = apt ]; then
    apt_native update
    apt_native -y --no-install-recommends install ca-certificates curl gpg gpgv
elif [ "$manager" = dnf ]; then
    dnf -y install ca-certificates gnupg2
    # Enterprise Linux may provide curl through curl-minimal already.
    command -v curl >/dev/null 2>&1 || dnf -y install curl
else
    zypper --non-interactive install --no-recommends ca-certificates curl gpg2
fi
curl --fail --silent --show-error --proto '=https' --tlsv1.2 "$base/schip.asc" -o "$temporary/key.asc"
mkdir -m700 "$temporary/gnupg"
actual=$(gpg --batch --homedir "$temporary/gnupg" --with-colons --import-options show-only --import "$temporary/key.asc" | awk -F: '$1=="fpr" { print $10; exit }')
[ "$actual" = "$fingerprint" ] || { echo 'Chave Schip inesperada.' >&2; exit 1; }
gpg --batch --yes --dearmor -o "$temporary/keyring.gpg" "$temporary/key.asc"
verifier=$(command -v gpgv || command -v gpgv2)
curl --fail --silent --show-error "$base/manifest.json" -o "$temporary/manifest.json"
curl --fail --silent --show-error "$base/manifest.json.asc" -o "$temporary/manifest.json.asc"
"$verifier" --homedir "$temporary/gnupg" --keyring "$temporary/keyring.gpg" "$temporary/manifest.json.asc" "$temporary/manifest.json"
# Verify metadata for the exact tuple before changing persistent configuration.
# The installer and native agent do not require a Python runtime.
if [ "$manager" = apt ]; then
    curl --fail --silent --show-error "$base/$distro/$version/apt/dists/schip/InRelease" -o "$temporary/InRelease"
    "$verifier" --homedir "$temporary/gnupg" --keyring "$temporary/keyring.gpg" "$temporary/InRelease"
    awk -v arch="$debarch" '$1=="Architectures:" {for(i=2;i<=NF;i++)if($i==arch)found=1} END {exit !found}' "$temporary/InRelease"
else
    rpmfingerprint=0437B243A2D5D257A6D974445EC1DF0459CFAF3D
    curl --fail --silent --show-error "$base/schip-rpm.asc" -o "$temporary/rpm-key.asc"
    mkdir -m700 "$temporary/rpm-gnupg"
    actual=$(gpg --batch --homedir "$temporary/rpm-gnupg" --with-colons --import-options show-only --import "$temporary/rpm-key.asc" | awk -F: '$1=="fpr" { print $10; exit }')
    [ "$actual" = "$rpmfingerprint" ] || { echo 'Chave RPM Schip inesperada.' >&2; exit 1; }
    gpg --batch --yes --dearmor -o "$temporary/rpm-keyring.gpg" "$temporary/rpm-key.asc"
    metadata=$base/$distro/$version/rpm/$rpmarch/repodata/repomd.xml
    curl --fail --silent --show-error "$metadata" -o "$temporary/repomd.xml"
    curl --fail --silent --show-error "$metadata.asc" -o "$temporary/repomd.xml.asc"
    "$verifier" --homedir "$temporary/gnupg" --keyring "$temporary/rpm-keyring.gpg" "$temporary/repomd.xml.asc" "$temporary/repomd.xml"
fi
if [ "$manager" = apt ]; then
    mkdir -p /etc/apt/keyrings
    gpg --batch --yes --dearmor -o /etc/apt/keyrings/schip-linux-agents.gpg "$temporary/key.asc"
    chmod 644 /etc/apt/keyrings/schip-linux-agents.gpg
    printf 'deb [arch=%s signed-by=/etc/apt/keyrings/schip-linux-agents.gpg] %s/%s/%s/apt schip main\n' "$debarch" "$base" "$distro" "$version" > /etc/apt/sources.list.d/schip-linux-agents.list
    if [ -f "$temporary/ubuntu-native.list" ]; then
        cat /etc/apt/sources.list.d/schip-linux-agents.list >> "$temporary/ubuntu-native.list"
    fi
    apt_native -o APT::Update::Error-Mode=any update
    apt_native -y --no-remove install schipsave-agent
else
    install -m644 "$temporary/rpm-key.asc" /etc/pki/rpm-gpg/RPM-GPG-KEY-schip 2>/dev/null || {
        mkdir -p /etc/pki/rpm-gpg
        install -m644 "$temporary/rpm-key.asc" /etc/pki/rpm-gpg/RPM-GPG-KEY-schip
    }
    rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-schip
    if [ "$manager" = dnf ]; then
        case "$distro" in
            almalinux|rocky|centos)
                dnf -y install dnf-plugins-core epel-release
                [ "$distro:$version" != centos:8 ] || cp /etc/yum.repos.d/epel*.repo "$temporary/native-repos/"
                if [ "$version" = 8 ]; then dnf config-manager --set-enabled powertools; else dnf config-manager --set-enabled crb; fi
                ;;
            rhel)
                dnf -y install dnf-plugins-core
                builder=$(dnf repolist --all | awk '/codeready/ {print $1;exit}')
                [ -z "$builder" ] || dnf config-manager --set-enabled "$builder"
                case "$version" in
                    8) epelfp=94E279EB8D8F25B21810ADF121EA45AB2F86D6A1 ;;
                    9) epelfp=FF8AD1344597106ECE813B918A3872BF3228467C ;;
                    10) epelfp=7D8D15CBFC4E62688591FB2633D98517E37ED158 ;;
                    *) echo 'Versao RHEL sem chave EPEL homologada' >&2;exit 1 ;;
                esac
                curl --fail --silent --show-error "https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-$version" -o "$temporary/epel.asc"
                mkdir -m700 "$temporary/epel-gnupg"
                actual=$(gpg --batch --homedir "$temporary/epel-gnupg" --with-colons --import-options show-only --import "$temporary/epel.asc" | awk -F: '$1=="fpr" {print $10;exit}')
                [ "$actual" = "$epelfp" ] || { echo 'Chave EPEL inesperada' >&2;exit 1; }
                rpm --import "$temporary/epel.asc"
                curl --fail --silent --show-error "https://dl.fedoraproject.org/pub/epel/epel-release-latest-$version.noarch.rpm" -o "$temporary/epel-release.rpm"
                rpmkeys --checksig "$temporary/epel-release.rpm"
                dnf -y --setopt=localpkg_gpgcheck=1 install "$temporary/epel-release.rpm"
                ;;
        esac
        repodir=/etc/yum.repos.d
    else
        repodir=/etc/zypp/repos.d
    fi
    mkdir -p "$repodir"
    cat > "$repodir/schip-linux-agents.repo" <<EOF
[schip-linux-agents]
name=Schipsave Linux Agents
baseurl=$base/$distro/$version/rpm/$rpmarch
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-schip
EOF
    [ "$distro:$version" != centos:8 ] || cp "$repodir/schip-linux-agents.repo" "$temporary/native-repos/"
    if [ "$manager" = dnf ]; then
        dnf -y --refresh install schipsave-agent
    else
        zypper --gpg-auto-import-keys --non-interactive refresh schip-linux-agents
        zypper --non-interactive install schipsave-agent
    fi
fi
schipsave --version
echo 'Agente instalado. Cadastre a maquina no painel e verifique a chave SSH.'
