#!/bin/bash

# Временная метка
timestamp=$(date +"%Y%m%d_%H%M%S")
log_file="/tmp/lc_install_additional_packages_$timestamp.log"

# Функция логирования
log() {
    echo "$1"
    echo "$1" >> "$log_file"
}

log "=========================================================================="
log "=== Preseed LC install_additional_packages script (network). Version 1 ==="
log "=========================================================================="

# Время старта скрипта (в секундах с начала эпохи)
start_time=$(date +%s)

# Глобальный этап миграции
step="di_lc_install_additional_packages"
hb_url="http://almigrlog01.bankexp.local/api/hb"
hostname="$(hostname)"

# Heartbeat start
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
wget --timeout=5 --tries=2 "$hb_url/?step=$step&state=start&action=install_additional_packages&elapsed=$elapsed_time&hostname=$hostname" -q -O /dev/null || true
log "Heartbeat start sent"

# === NVIDIA driver check ===
excluded_ids="10de:1058"

log "==== NVIDIA driver check started ===="

lspci_output="$(lspci -n)"
log "lspci output:"
log "$lspci_output"

if echo "$lspci_output" | grep -q '^.* 0300: 10de:.*$'; then
    log "NVIDIA GPU detected, processing NVIDIA driver installation"
    match_excluded=false

    for id in $excluded_ids; do
        log "Checking excluded ID: $id"
        if echo "$lspci_output" | grep -q "$id"; then
            log "Match found for excluded ID: $id"
            match_excluded=true
            matched_id=$id
            break
        else
            log "No match for excluded ID: $id"
        fi
    done

    if [ "$match_excluded" = false ]; then
        log "Supported NVIDIA GPU detected, installing nvidia-driver-525"
        apt install -y nvidia-driver-525 >> "$log_file" 2>&1
        log "nvidia-driver-525 installation finished"
    else
        log "Excluded NVIDIA GPU ($matched_id) detected, skipping driver installation"
    fi
else
    log "No NVIDIA GPU detected, skipping NVIDIA driver installation"
fi

# === Heartbeat stop ===
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
wget --timeout=5 --tries=2 "$hb_url/?step=$step&state=stop&action=install_additional_packages&elapsed=$elapsed_time&hostname=$hostname" -q -O /dev/null || true
log "Heartbeat stop sent"
