#!/bin/bash

progname=$0
usage() {
    echo "usage: $0 [-f|-h]"
    echo "  -f  force run this script even system is not up-to-date"
    echo "  -h  display help"
    exit 1
}

### main ###

# accept optional params
force_run=0
while getopts "fh" opt; do
    case $opt in
        f)
            force_run=1
            ;;
        h)
            usage
            ;;
        \?)
            ;;
    esac
done

# root is required
if [ $(id -u) -ne 0 ]; then
    echo "Fatal: root is required to run this script."
    exit 255
fi

# discontinue if current system is not CentOS 8, just in case
if [ ! -f /etc/centos-release ] || ! grep -q 'CentOS Linux release 8' /etc/centos-release; then
    echo "Fatal: secto service should run on CentOS 8 Linux only."
    exit 255
fi


# discontinue if centos 8 is not update to date, and force run if force_run given
if ! grep -q 'CentOS Linux release 8.5' /etc/centos-release; then
    if [ x"$force_run" != x1 ]; then
        echo "Fatal: your CentOS 8 Linux is not up-to-date, we recommend you update your"
        echo "       system before running this script. run 'yum update -y' then reboot"
        echo "       your system, or giving '-f' to force run secto service."
        exit 1
    else
        echo "Warn: your CentOS 8 Linux is not up-to-date, we recommend you update your"
        echo "      system before running this script. '-f' option given, force run."
    fi
fi

# Refresh repo cache, install compatiable packages for platform
arch=$(uname -m)
SECTO_URL=https://mirrors.openanolis.cn/centostakeover/8/BaseOS/$arch/os/Packages/
COMPAT_RPMS=$(dnf repoquery --latest-limit 1 --repoid metarel1 \
--repofrompath=metarel1,https://mirrors.openanolis.cn/centostakeover/8/BaseOS/aarch64/os/ \
-q -a --qf '%{name}-%{version}-%{release}.%{arch}.rpm'| \
grep -P "(json-c|json-glib|python3-hawkey|libdnf)")

yum install -y $(echo "$COMPAT_RPMS" | xargs -i echo -n "$SECTO_URL/{} ")

sed -i "s/^enabled=0$/enabled=1/g" /etc/yum.repos.d/AnolisOS-Secto.repo 
yum makecache
yum install libdnf python3-hawkey python3-libdnf setup -y
yum module reset llvm-toolset -y
