#!/bin/bash
set -exu

days=5

URL="http://repo.os.mos.ru/mos13/.sync-marker"
error_reason=""

curl_status=0
headers=$(curl -I -s --fail "$URL") || curl_status=$?
date_line=""

if [ "$curl_status" -ne 0 ] || [ -z "$headers" ]
then
    error_reason="не доступен адрес http://repos.os.mos.ru/mos13/.sync-marker"
else
    date_line=$(echo "$headers" | grep -i '^Date:') ||:
    if [ -z "$date_line" ]; then
        error_reason="не доступен адрес http://repos.os.mos.ru/mos13/.sync-marker"
    else
        repo_date_str=$(echo "$date_line" | sed 's/^[Dd]ate: //')
        repo_date_ts=$(date -d "$repo_date_str" +%s)
        current_ts=$(date +%s)

        diff=$((current_ts - repo_date_ts))
        time_days=$((days * 24 * 3600))

        if [ "$diff" -gt "$time_days" ]; then
            error_reason="sync-marker старше $days дней ($repo_date_str)"
        fi
    fi
fi

repo_ip=$(getent hosts repo.os.mos.ru 2>/dev/null | awk '{print $1}' | head -n1) ||:
if [ -z "$repo_ip" ]; then
    repo_ip="не определён"
    if [ -z "$error_reason" ]; then
        error_reason="не удаётся получить ip"
    fi
fi

if [ -n "$error_reason" ]; then
    echo -e "\n\n\e[31mОбнаружены проблемы с сервером репозитория (IP: $repo_ip).\nНапишите в техподдержку, чтобы проверили сервер репозитория с которого Вы получаете обновления!\n\nОшибка: $error_reason\e[0m\n\n"
    exit 1
fi

echo "Сервер репозитория в порядке!"

# Обновляем систему, версию ядра и версии всех пакетов приводим к актуальным
dnf update -y
dnf install -y task-kernel-6.12-generic
dnf dsync -y

# Удаляем Агент Ассистента со всеми его данными
dnf rm -y uds-system-agent
rm -rf /etc/uds-system-agent

# Устанавливаем Агент Ассистена и пакет mos-identify
dnf in -y uds-system-agent mos-identify
systemctl start uds-system-agent.service

# Удаляем pro32connect и файл с настройками
dnf rm -y dit-support
rm -f /var/lib/pro32connect/settings.dat

# Устанавливаем pro32connect и стартуем службу
dnf in -y dit-support
systemctl enable --now pro32connect

# Ожидаем стабилизации работы pro32connect и Агента Ассистента
sleep 10s

# Регистрируемся в https://rcc.mos.ru
timeout 10s /opt/dit-support/dit-support -register administrator:1 ||:

# Обновляем id pro32connect в Ассистенте
systemctl stop uds-system-agent
rm -f /etc/mosinv.md5
rm -f /etc/device_activity.hash
systemctl start uds-system-agent

# Обязательная перезагрузка
reboot
