#!/bin/bash

# Developed by Daniel-Alf Junghänel - DAJ_Linux and Kevin CHEVREUIL - Kaisen for the kaisen-timeshift-apt package

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
YELLOW='\e[0;33m'
RED='\e[1;31m'
RESET_COLOR='\033[0m'

# Check if exec in a chroot
if [ "$(stat -c %d:%i /)" != "$(stat -c %d:%i /proc/1/root/.)" ]; then
        echo -e $YELLOW "Running in chroot, ignore the snapshot deletion request."$RESET_COLOR
        exit 0
fi

# Check the presence of the timeshift command
if ! command -v timeshift > /dev/null; then
        echo -e $RED "The timeshift command was not found. Aborting."$RESET_COLOR
        exit 0
fi

# If the script is executed from the overlayfs mounted by the grub when booted from a snapshot, exit.
cat /proc/cmdline | grep kaisen-grub-btrfs > /dev/null

if [ $? -eq 0 ]; then
	echo -e $RED "You have booted from a snapshot. Aborting."$RESET_COLOR
	exit 0
fi

# Define the time, after that the snapshots get deleted
# 7 days have 604800 seconds
# 14 days have 1209600 seconds
RETENTION=604800

# Check which partition or UUID is /
DEVICE=$(grep -v '#' /etc/fstab | grep -w / | grep -w subvol=@ | cut -d ' ' -f1 | cut -d '=' -f2)

# Get array with APT snapshots
SNAPSHOTS=$(timeshift --scripted --btrfs --list --snapshot-device "$DEVICE" | grep "Automatic APT snapshot" | awk '{ print $3 }')

# Calculate the time now, multiple days in the past to epoch seconds
PASTTIME=$(($(date '+%s')-"$RETENTION"))

# Main logic
for SNAPSHOT in $SNAPSHOTS
do
  # Convert the snapshot time to epoch seconds
  SNAPTIME=$(date '+%s' -d "${SNAPSHOT:0:4}${SNAPSHOT:5:2}${SNAPSHOT:8:2} ${SNAPSHOT:11:2}:${SNAPSHOT:14:2}:${SNAPSHOT:17:2}")
  # Compare the time
  RESULT=$(("$SNAPTIME"-"$PASTTIME"))
  # If the result is smaller zero, delete it!
  if [ "$RESULT" -lt 0 ]; then
    echo -e $YELLOW "Snapshot $SNAPSHOT gets deleted!"$RESET_COLOR
    timeshift --delete --scripted --btrfs --yes --snapshot "$SNAPSHOT" --snapshot-device "$DEVICE"
  else
    echo "Snapshot $SNAPSHOT not old enough!"
  fi
done
