#!/bin/bash

set -e

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

if [ "$EUID" -ne "0" ]; then
	echo -e $RED "Run this script as root or with the sudo command."$RESET_COLOR
	exit 1
fi

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

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

#Check if / use BTRFS as filesystem to remove kaisen-btrfs-snapshots if BTRFS not use
CHECK_SUBVOL=`grep -v '#' /etc/fstab | grep -w / | grep -wo subvol=@ || true`
CHECK_MOUNT=`grep -o "/ btrfs" /proc/mounts 2> /dev/null || true`

if [ "$CHECK_SUBVOL" = "subvol=@" 2> /dev/null ] && [ "$CHECK_MOUNT" = "/ btrfs" 2> /dev/null ]; then
	btrfs quota disable / 2> /dev/null || true
	btrfs quota disable /home 2> /dev/null || true
	timeshift --scripted --yes --btrfs --create --comments "Automatic APT snapshot"
fi
