#!/bin/bash
LOG_FILE="/var/log/dm-scripts.log"
BASESCRIPT=$(realpath /usr/libexec/dm-script-link)

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

cleanup() {
    log "Read DM Scripts log and press ENTER to return DM"
    read qqq
    systemctl start display-manager.service
}

# Если мы не в 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 dm_scripts -n upgrade "bash '$0' $@"
    exit 0
else
    chvt 1
fi

main() {
    date > $LOG_FILE

    if [ -n "$TMUX" ]; then
        tmux rename-window "DM Scripts"
    fi

    echo "========================="
    log "    Run: $BASESCRIPT     "
    echo "========================="
    echo ""

    $BASESCRIPT | tee -a $LOG_FILE
    [ "${PIPESTATUS[0]}" -eq 0 ] && 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
