#!/bin/bash
set -e

if [[ $EUID -ne 0 ]]; then
   echo "Этот скрипт должен быть выполнен от суперпользователя"
   exit 1
fi

# Detecting the OS
source /etc/os-release || true
if [[ ( -z "$VERSION_ID" && -z "$VERSION_CODENAME" ) || -z "$ID" ]]; then
    echo "Не удалось определить операционную систему"
    exit 1
fi

echo "Обнаруженная ОС: $ID $VERSION_ID"

REPOS_SOURCE=https://repo.nanodev.ru/r26.0

install_package() {
    PACKAGE_MANAGER=$1
    PACKAGE_NAME=$2
    $PACKAGE_MANAGER install $PACKAGE_NAME -y
}

make_repo_file() {
    DISTNAME=$1
    cat <<EOF > /etc/yum.repos.d/nanodev260.repo
[nanodev260]
name=nanoCAD 26.0 builds
baseurl=$REPOS_SOURCE/$DISTNAME/
gpgcheck=1
gpgkey=$REPOS_SOURCE/$DISTNAME/repodata/repomd.xml.key
enabled=1
EOF
}

case "$ID $VERSION_ID" in
    "redos 7.3"*|"redos 8.0"*|"altlinux 10"*|"altlinux 11"*|"astra 1.7_x86-64"|"astra 1.8_x86-64"|"ubuntu 24.04"|"alteros 9"*) SUPPORTED=true ;;
    *) SUPPORTED=false ;;
esac

if [[ $SUPPORTED != true ]]; then
    echo "Ваша операционная система не поддерживается"
    exit 1
fi

echo "Добавление репозитория nanoCAD 26.0..."

if [[ "$ID $VERSION_ID" == "altlinux 10"* ]]; then
    echo "rpm ${REPOS_SOURCE}/Alt_p10/ x86_64 nanodev" > /etc/apt/sources.list.d/nanodev260.list
elif [[ "$ID $VERSION_ID" == "altlinux 11"* ]]; then
    echo "rpm ${REPOS_SOURCE}/Alt_p11/ x86_64 nanodev" > /etc/apt/sources.list.d/nanodev260.list
elif [[ "$ID $VERSION_ID" == "astra 1.8_x86-64" ]]; then
    wget --no-check-certificate -qO /tmp/nanosoft.key ${REPOS_SOURCE}/AstraLinuxSE_1.8/Release.key
    gpg --dearmor /tmp/nanosoft.key
    mv /tmp/nanosoft.key.gpg /etc/apt/trusted.gpg.d/ &>/dev/null || :
    wget -qO- ${REPOS_SOURCE}/AstraLinuxSE_1.8/nanosoft.asc > /etc/apt/trusted.gpg.d/nanosoft.asc
    echo "deb ${REPOS_SOURCE}/AstraLinuxSE_1.8  ./" > /etc/apt/sources.list.d/nanodev260.list
elif [[ "$ID $VERSION_ID" == "astra 1.7_x86-64" ]]; then
    wget ${REPOS_SOURCE}/AstraLinuxSE_1.7/Release.key --no-check-certificate -qO- | apt-key add
    echo "deb ${REPOS_SOURCE}/AstraLinuxSE_1.7/ ./" > /etc/apt/sources.list.d/nanodev260.list
elif [[ "$ID $VERSION_ID" == "redos 7.3"* ]]; then
    make_repo_file "redOS_7.3"
elif [[ "$ID $VERSION_ID" == "redos 8.0"* ]]; then
    make_repo_file "redOS_8.0"
elif [[ "$ID $VERSION_ID" == "alteros 9"* ]]; then
    make_repo_file "AlterOS_9"
elif [[ "$ID" == "ubuntu" ]]; then
    wget --no-check-certificate -qO /tmp/nanosoft.key ${REPOS_SOURCE}/Ubuntu_$VERSION_ID/Release.key
    gpg --dearmor /tmp/nanosoft.key
    mv /tmp/nanosoft.key.gpg /etc/apt/trusted.gpg.d/ &>/dev/null || :
    wget -qO- ${REPOS_SOURCE}/Ubuntu_$VERSION_ID/nanosoft.asc > /etc/apt/trusted.gpg.d/nanosoft.asc
    echo "deb ${REPOS_SOURCE}/Ubuntu_$VERSION_ID /" > /etc/apt/sources.list.d/nanocad260.list
fi


if [[ "$ID" =~ ^(redos)$ || "$ID $VERSION_ID" == "alteros 9"* ]]; then
    PACKAGE_MANAGER="dnf"
elif [[ "$ID" =~ ^(astra|altlinux|ubuntu)$ ]]; then
    apt-get update
    PACKAGE_MANAGER="apt-get"
fi

packages=(
    "ncad-mech26-0|Модуль «Механика»"
    "ncad-spds26-0|Модуль «СПДС»"
    "ncad-ssbadmin26-0|Модуль «Организация» - Администратор"
    "nanolm-nanosoft|Сервер лицензий Нанософт nanoLM"
)

if [[ "$PACKAGE_MANAGER" == "apt-get" ]]; then
    AVAILABLE_PACKAGES=$(apt-cache search '^(ncad|geonics|nanolm-nanosoft)(-(digsig|mech|spds|ssbadmin|topography|routes|reclouds|metrology|gtm))?(26-0)?(-oe)?$' | awk '{print $1}' | tr '\n' ' ') 
elif [[ "$PACKAGE_MANAGER" == "dnf" ]]; then
    AVAILABLE_PACKAGES=$(dnf list | grep -E "(ncad|geonics|nanolm-nanosoft)(-(digsig|mech|spds|ssbadmin|topography|routes|reclouds|metrology|gtm))?(26-0)?(-oe)?\.x86_64" | sed 's/\.x86_64//' | awk '{print $1}' | tr '\n' ' ')
fi

declare -A available

for p in $AVAILABLE_PACKAGES; do
    available["$p"]=1
done

filtered_packages=()

for entry in "${packages[@]}"; do
    pkg="${entry%%|*}"
    if [[ -n "${available[$pkg]}" ]]; then
        filtered_packages+=("$entry")
    fi
done

packages=("${filtered_packages[@]}")

show_packages() {
    echo "Дополнительные пакеты:"
    for i in "${!packages[@]}"; do
        IFS='|' read -ra parts <<< "${packages[i]}"
        printf "%2d) %s - %s\n" $((i+1)) "${parts[0]}" "${parts[1]}"
    done
}

get_package_name() {
    IFS='|' read -ra parts <<< "${packages[$1]}"
    echo "${parts[0]}"
}


read -rp "Желаете установить nanoCAD? [д/Н]: " choice </dev/tty

case "$choice" in
    [yYдД])
        while true; do
            show_packages
            echo -e "\n==> Введите номера устанавливаемых пакетов (пример: '1 2 3', '1-3', '2 4')"
            echo -e "==> или оставьте пустым для установки только платформы nanoCAD 26.0"
            read -rp "==> " input </dev/tty

            if [[ -z "$input" ]]; then
                break
            fi

            cleaned_input=$(echo "$input" | tr -s ', ' ' ')
            declare -a selections
            valid=true

            for part in $cleaned_input; do
                if [[ $part =~ ^([0-9]+)-([0-9]+)$ ]]; then
                    start=${BASH_REMATCH[1]}
                    end=${BASH_REMATCH[2]}
                    
                    if (( start > end || end > ${#packages[@]} || start < 1 )); then
                        echo "Ошибка: Некорректный диапазон '$part'"
                        valid=false
                        break
                    fi
                    
                    selections+=()
                    while IFS='' read -r line; do selections+=("$line"); done < <(seq "$start" "$end")
                elif [[ $part =~ ^[0-9]+$ ]]; then
                    if (( part < 1 || part > ${#packages[@]} )); then
                        echo "Ошибка: Некорректный номер '$part'"
                        valid=false
                        break
                    fi
                    selections+=("$part")
                else
                    echo "Ошибка: Недопустимый формат '$part'"
                    valid=false
                    break
                fi
            done

            if $valid; then
                unique_selections=()
                while IFS='' read -r line; do unique_selections+=("$line"); done < <(printf "%s\n" "${selections[@]}" | sort -nu)
                selected_packages=()
                
                for i in "${unique_selections[@]}"; do
                    selected_packages+=("$(get_package_name $((i-1)))")
                done

                echo -e "\nВыбраны пакеты:"
                printf " - %s\n" "${selected_packages[@]}"
                break
            else
                echo -e "\nПожалуйста, введите правильные значения...\n"
                sleep 1
            fi
        done
        install_package "$PACKAGE_MANAGER" "ncad-pgsql16"
        install_package "$PACKAGE_MANAGER" "ncad26-0 ${selected_packages[*]}"
        ;;
    *)
        echo "Чтобы установить nanoCAD, выполните следующие команды:"
        echo "    sudo $PACKAGE_MANAGER install ncad-pgsql16"
        echo "    sudo $PACKAGE_MANAGER install ncad26-0"
        show_packages
esac
