#!/bin/bash
LOG_FILE="/var/log/kde-switcher.log"
BASESCRIPT='update-kde5-to-kde6'
[ -f /etc/kde-switcher ] && . /etc/kde-switcher

log() {
    echo "==> $1"
    echo "$(date '+%H:%M:%S') ==> $1" >> "$LOG_FILE"
}

cleanup() {
    log "Read Kde Switcher log and press ENTER to reboot"
    read qqq
    log "Rebooting system..."
    sync
    reboot || reboot -f
}

check_network() {
    log "Checking network connectivity..."

    # Check net
    if ! ping -c 2 -W 5 77.88.8.8 >/dev/null 2>&1 && \
       ! ping -c 2 -W 5 8.8.8.8 >/dev/null 2>&1; then
        log "Network check failed"
        read qqq
        exit 1
    fi

    # Check DNS
    if ! nslookup rosa.ru >/dev/null 2>&1; then
        log "DNS check warning"
    fi

    log "Network check passed"
}

# Если мы не в tmux и tmux доступен - перезапускаемся в tmux
if [ -z "$TMUX" ] && command -v tmux >/dev/null 2>&1; then
    log "Restarting in tmux session"
    chvt 1
    clear
    exec tmux new-session -s kde_switcher -n upgrade "bash '$0' $@"
    exit 0
else
    chvt 1
fi

main() {
    $(date) > $LOG_FILE

    if [ -n "$TMUX" ]; then
        tmux rename-window "Kde Switcher"
    fi
    
    check_network
    echo "========================="
    echo "    Run: $BASESCRIPT     "
    echo "========================="
    echo ""

    log "Starting kde switch process"
    
    $BASESCRIPT && log "All commands completed successfully"
}

trap cleanup EXIT

if [ "$(id -u)" -ne 0 ]; then
    echo "You must be root to run this script" >&2
    exit 1
fi

main
