#!/bin/bash
# -----------------------------------------------------------------------------
# GuideOS Snapshot-Manager
# -----------------------------------------------------------------------------
# GUI-Frontend für Timeshift
# - Snapshots erstellen
# - Snapshots löschen
# - Anzeige von Snapshots mit Datum und Kommentar
# - Einfache Bedienung über Zenity
# -----------------------------------------------------------------------------
# Hinweis:
# Vor der Nutzung Timeshift einmalig einrichten:
# 1. Alle Snapshot-Intervalle anhaken
# 2. Home-Verzeichnis NICHT sichern (vermeidet große Snapshots)
# -----------------------------------------------------------------------------
# Autor: evilware666
# Lizenz: MIT
# -----------------------------------------------------------------------------

# ========================= Systemprüfung =========================
ROOT_FS=$(findmnt -n -o FSTYPE /)
if [ "$ROOT_FS" != "btrfs" ]; then
    zenity --error --title="Fehler: Nicht-Btrfs-System" \
        --text="Dieses Tool kann nur auf Systemen mit Btrfs-Dateisystem ausgeführt werden.\nDein System verwendet: $ROOT_FS"
    exit 1
fi

if [ -d "/cdrom" ] || grep -q "boot=live" /proc/cmdline; then
    zenity --error --title="Fehler: Live-System" \
        --text="Dieses Tool sollte nicht im Live-System ausgeführt werden."
    exit 1
fi
# =================================================================


zenity --info --title="GuideOS Snapshot-Manager - Einrichtungshinweis" \
--text="Für eine optimale Systemsicherung wird empfohlen, TimeShift wie folgt einzurichten.\n\n\
- Btrfs aktivieren\n- Alle Snapshot-Intervalle anhaken\n- Home-Verzeichnis NICHT sichern\n\n\
Damit ist das System vollständig abgesichert, da TimeShift neben den manuell erstellten Snapshots auch automatisch welche anlegt." \
--ok-label="OK" --width=700 --height=400


export G_MESSAGES_DEBUG=none
TITLE="GuideOS Snapshot-Manager"

PLAY_SOUND() {
  if command -v paplay >/dev/null 2>&1 && [ -f "/usr/share/cinnamon/sounds/bell.ogg" ]; then
    paplay "/usr/share/cinnamon/sounds/bell.ogg" 2>/dev/null &
  fi
}

PASSWORT=$(zenity --password --title="Authentifizierung erforderlich" --text="Bitte das Passwort des aktuellen Benutzers eingeben:")
if [ -z "$PASSWORT" ]; then
  zenity --error --title="Abgebrochen" --text="Kein Passwort eingegeben."
  exit 1
fi

run_sudo_bash() {
  echo "$PASSWORT" | sudo -S -p '' bash -c "$1"
}

get_snapshots() {
  OUT=$(echo "$PASSWORT" | sudo -S -p '' timeshift --list 2>/dev/null || true)
  result=""
  while IFS= read -r line; do
    id=$(printf "%s" "$line" | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}[_-][0-9]{2}-[0-9]{2}-[0-9]{2}' || true)
    if [ -n "$id" ]; then
      comment=$(printf "%s" "$line" | sed "s/.*$id[[:space:]]*//" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
      [ -z "$comment" ] && comment="(kein Kommentar)"
      display=$(printf "%s" "$id" | sed -E 's/_/ /; s/([0-9]{2})-([0-9]{2})-([0-9]{2})$/\1:\2:\3/')
      result+="$id|$display|$comment"$'\n'
    fi
  done <<< "$OUT"
  printf "%s" "$result"
}

create_snapshot() {
  SNAP_NAME=$(zenity --entry --title="Snapshot-Name" --text="Gib einen Namen für den Snapshot ein (optional):")
  [ $? -ne 0 ] && return
  [ -z "$SNAP_NAME" ] && SNAP_NAME="Manueller Snapshot"

  zenity --info --title="Snapshot" --text="Snapshot wird erstellt — bitte warten..."
  run_sudo_bash "timeshift --create --comments \"${SNAP_NAME}\" --yes" > /tmp/timeshift_create.log 2>&1
  rc=$?
  if [ $rc -eq 0 ]; then
    zenity --info --title="Fertig" --text="Snapshot '$SNAP_NAME' erfolgreich erstellt."
    PLAY_SOUND complete
    run_sudo_bash "update-grub" > /tmp/update_grub_create.log 2>&1
    zenity --info --title="GRUB aktualisiert" --text="GRUB-Konfiguration wurde nach dem Snapshot aktualisiert."
  else
    zenity --text-info --title="Fehler bei Erstellung" --filename=/tmp/timeshift_create.log --width=800 --height=400
    PLAY_SOUND dialog-error
  fi
}

delete_snapshot() {
  entries=$(get_snapshots)
  [ -z "$entries" ] && zenity --info --title="Löschen" --text="Keine Snapshots vorhanden." && return

  sorted_entries=$(printf "%s" "$entries" | sort -r)
  counter=1
  args=()
  declare -A id_map

  while IFS='|' read -r id display comment; do
    display_id="GuideOS-Snapshot $counter"
    args+=("$display_id" "$display${comment:+ — $comment}")
    id_map["$display_id"]="$id"
    ((counter++))
  done <<< "$sorted_entries"

  selected=$(zenity --list --title="Snapshot löschen" --text="Wähle Snapshot zum Löschen:" \
            --column="Snapshot-ID" --column="Snapshots (Datum & Name)" \
            "${args[@]}" --height=450 --width=800)
  [ -z "$selected" ] && return

  selected_id="${id_map[$selected]}"
  zenity --question --title="Bestätigung" --text="Snapshot\n${selected}\nwirklich löschen?" --ok-label="Ja" --cancel-label="Nein"
  [ $? -ne 0 ] && return

  run_sudo_bash "timeshift --delete --snapshot \"$selected_id\" --yes" > /tmp/timeshift_delete.log 2>&1
  rc=$?
  if [ $rc -eq 0 ]; then
    zenity --info --title="Gelöscht" --text="Snapshot '${selected}' wurde gelöscht."
    PLAY_SOUND complete
    run_sudo_bash "update-grub" > /tmp/update_grub_delete.log 2>&1
    zenity --info --title="GRUB aktualisiert" --text="GRUB-Konfiguration wurde nach dem Löschen aktualisiert."
  else
    zenity --text-info --title="Fehler beim Löschen" --filename=/tmp/timeshift_delete.log --width=800 --height=400
    PLAY_SOUND dialog-error
  fi
}

main_menu() {
  while true; do
    choice=$(zenity --list --title="$TITLE" --text="Was möchtest du tun?" \
      --column="Aktion" --height=300 --width=500 \
      "Snapshot erstellen" "Snapshot löschen" "Beenden")

    case "$choice" in
      "Snapshot erstellen") create_snapshot ;;
      "Snapshot löschen") delete_snapshot ;;
      "Beenden") exit 0 ;;
      *) break ;;
    esac
  done
}

main_menu
