#!/bin/sh

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

# Временная метка
timestamp=$(date +"%Y%m%d_%H%M%S")
# Лог-файл с временной меткой
log_file="/tmp/ec_get_bootdisk_$timestamp.log"

# Глобальный этап миграции
step="di_partman_ec_get_bootdisk"
# Heart beat сервер
hb_url="http://repo.redtux.su/hb"
# Имя хоста
hostname=$(hostname)

# Функция для вывода в консоль и запись в лог-файл
log() {
    echo "$1"
    echo "$1" >> "$log_file"
}

log "==================================================================="
log "=== Preseed Partman EC get-bootdisk script (network). Version 2 ==="
log "==================================================================="


# Текущий elapsed_time
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
# Heart beat
wget --timeout=5 --tries=2 "$hb_url/?step=$step&state=start&action=ec_get-bootdisk&elapsed=$elapsed_time&hostname=$hostname" -q -O /dev/null || true

# Получаем параметр install_mode из /proc/cmdline
install_mode=$(tr ' ' '\n' < /proc/cmdline | grep '^install_mode=' | cut -d'=' -f2)
install_mode=$(echo $install_mode | cut -c1-2)
# Если install_mode не задан — выводим ошибку и перезагружаем систему
if [ -z "$install_mode" ]; then
    . /usr/share/debconf/confmodule
    cat > /tmp/InstallModeError.template <<'!EOF!'
Template: install-mode/error
Type: error
Description: ERROR - install_mode parameter is missing.
 The installation cannot continue without specifying install_mode.
 Please check boot parameters in GRUB configuration.
 Remove installation media.
 System will reboot now.
!EOF!
    debconf-loadtemplate install-mode /tmp/InstallModeError.template
    while true; do
        db_title Install Mode Missing
        db_input critical install-mode/error || true
        db_go
        /sbin/shutdown -r now
        sleep 10
    done
fi

log "install_mode detected: $install_mode"


fullname=$(blkid -t LABEL="migrate" -o device)

if [ -z "$fullname" ]; then
    log "Error: No disk with label 'migrate' found. Aborting ALSE installation..."
    exit 1
else
    boot_disk=$(
        if [ "${fullname#/dev/n}" != "$fullname" ]; then
            echo "$fullname" | head -c12
        else
            echo "$fullname" | head -c8
        fi
    )
fi

log "fullname = $fullname"
log "boot_disk = $boot_disk"

# Выбор метки разделов (GPT для EFI, MSDOS для Legacy)
if [ -d "/sys/firmware/efi" ]; then
    log "EFI system detected"
    debconf-set partman-partitioning/choose_label gpt
    debconf-set partman-partitioning/default_label gpt
else
    log "Legacy BIOS detected"
    debconf-set partman-partitioning/choose_label msdos
    debconf-set partman-partitioning/default_label msdos
fi

# Настройка рецепта разметки
if [ "$install_mode" = "db" ]; then
    # В режиме Dual Boot используем штатный рецепт atomic
    log "Mode 'db': selecting built-in 'atomic' recipe"
elif [ "$install_mode" = "sb" ] || [ "$install_mode" = "sb_lvrm" ]; then
    # Для sb используем LVM
    log "Mode 'sb': selecting LVM recipe"
    debconf-set partman-auto/method lvm
    if [ -d "/sys/firmware/efi" ]; then
        log "Configuring GPT LVM recipe"
        debconf-set partman-auto/expert_recipe \
        "boot-gpt-lvm :: \
            512 512 512 fat32 \
                \$iflabel{ gpt } method{ efi } format{ } mountpoint{ /boot/efi } filesystem{ vfat } . \
            1024 1024 1024 ext4 \
                method{ format } format{ } use_filesystem{ } filesystem{ ext4 } mountpoint{ /boot } . \
            100 1000 -1 lvm \
                method{ lvm } vg_name{ vg } . \
            100 1000 -1 ext4 \
                \$lvmok{ } in_vg{ vg } lv_name{ root } method{ format } format{ } use_filesystem{ } filesystem{ ext4 } mountpoint{ / } . \
            8192 8192 8192 linux-swap \
                \$lvmok{ } in_vg{ vg } lv_name{ swap } method{ swap } format{ } ."
        debconf-set partman-auto/choose_recipe boot-gpt-lvm
        log "UEFI GPT LVM recipe set"
    else
        log "Configuring MSDOS LVM recipe"
        debconf-set partman-auto/expert_recipe \
        "boot-legacy-lvm :: \
            1024 1024 1024 ext4 \
                \$primary{ } \$bootable{ } method{ format } format{ } use_filesystem{ } filesystem{ ext4 } mountpoint{ /boot } . \
            100 1000 -1 lvm \
                \$primary{ } method{ lvm } vg_name{ vg } . \
            100 1000 -1 ext4 \
                \$lvmok{ } in_vg{ vg } lv_name{ root } method{ format } format{ } use_filesystem{ } filesystem{ ext4 } mountpoint{ / } . \
            8192 8192 8192 linux-swap \
                \$lvmok{ } in_vg{ vg } lv_name{ swap } method{ swap } format{ } ."
        debconf-set partman-auto/choose_recipe boot-legacy-lvm
        log "Legacy MSDOS LVM recipe set"
    fi
fi

# Установка целевого диска для авторазметки и GRUB
if [ -n "$boot_disk" ]; then
    debconf-set partman-auto/disk "$boot_disk"
    log "Partitioning disk set to: $boot_disk"
    debconf-set grub-installer/bootdev "$boot_disk"
    log "GRUB boot device set to: $boot_disk"
else
    log "ERROR: boot_disk is empty, cannot configure partitioning"
fi

# Текущий elapsed_time
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
# Heart beat
wget --timeout=5 --tries=2 "$hb_url/?step=$step&state=stop&action=ec_get-bootdisk&elapsed=$elapsed_time&hostname=$hostname" -q -O /dev/null || true

# Завершение выполнения скрипта
log "Script execution completed"

exit 0
