#!/bin/bash
#  ____                        _           _
# / ___| _ __   __ _ _ __  ___| |__   ___ | |_
# \___ \| '_ \ / _` | '_ \/ __| '_ \ / _ \| __|
#  ___) | | | | (_| | |_) \__ \ | | | (_) | |_
# |____/|_| |_|\__,_| .__/|___/_| |_|\___/ \__|
#                   |_|
#
# Original by Stephan Raabe (2024)
# Extended for Fedora/openSUSE (2026)
# -----------------------------------------------------

sleep 1
clear
if command -v figlet &> /dev/null; then
    figlet -f smslant "Snapshot"
else
    echo "--- Snapshot Tool ---"
fi

# --- OS Detection & Package Manager Setup ---
if command -v pacman &> /dev/null; then
    OS="Arch"
    PKG_INST="pacman -S"
    CHECK_CMD="pacman -Qs"
    GRUB_CFG="/boot/grub/grub.cfg"
elif command -v dnf &> /dev/null; then
    OS="Fedora"
    PKG_INST="sudo dnf install"
    CHECK_CMD="rpm -q"
    GRUB_CFG="/boot/grub2/grub.cfg"
elif command -v zypper &> /dev/null; then
    OS="openSUSE"
    PKG_INST="sudo zypper install"
    CHECK_CMD="zypper se -i"
    GRUB_CFG="/boot/grub2/grub.cfg"
else
    echo "ERROR: Unsupported Distribution (No pacman, dnf, or zypper found)."
    exit 1
fi

_isInstalled() {
    $CHECK_CMD "$1" &> /dev/null
}

# --- Main Logic ---
if _isInstalled "timeshift"; then
    c=$(gum input --placeholder "Enter a comment for the snapshot...")
    sudo timeshift --create --comments "$c"
    sudo timeshift --list
    
    if [[ -f $GRUB_CFG ]]; then
        if ! _isInstalled "grub-btrfs"; then
            if gum confirm "grub-btrfs not found. DO YOU WANT TO INSTALL IT NOW?"; then
                $PKG_INST grub-btrfs
            else
                exit
            fi
        fi
        echo "Updating Grub configuration at $GRUB_CFG..."
        sudo grub-mkconfig -o "$GRUB_CFG"
    fi
    echo "DONE. Snapshot '$c' created and Grub updated!"
else
    echo "ERROR: Timeshift is not installed on $OS."
    if gum confirm "DO YOU WANT TO INSTALL Timeshift now?"; then
        $PKG_INST timeshift
        echo ":: Timeshift has been installed. Please restart this script."
        
        if ! _isInstalled "grub-btrfs"; then
            echo ":: grub-btrfs is recommended to select snapshots at boot."
            if gum confirm "DO YOU WANT TO INSTALL grub-btrfs now?"; then
                $PKG_INST grub-btrfs
            fi
        fi
    fi
fi