#!/bin/bash
#author: gobonja
#Modified by Matti Hyttinen

[ $(findmnt / -no fstype) == "overlay" ] && { echo "==> skipping timeshift-autosnap because system is booted in Live CD mode..."; exit 0; }
[[ -v SKIP_AUTOSNAP ]] && { echo "==> skipping timeshift-autosnap due SKIP_AUTOSNAP environment variable being set."; exit 0; }

readonly CONF_FILE=/etc/timeshift-autosnap.conf
readonly SNAPSHOTS_TO_DELETE=$(mktemp -u --tmpdir ${0##*/}.XXXXXXXX)

readonly SNAPSHOT_NAME_DATE_PATTERN="[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}_[0-9]\{2\}-[0-9]\{2\}-[0-9]\{2\}"

get_property() {
    if [ ! -f $CONF_FILE ]; then
        echo "$CONF_FILE not found! Using $1=$3" >&2;
        param_value=$3
    else
        param_value=`sed '/^\#/d' $CONF_FILE | grep $1 | tail -n 1 |\
        cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'`

        if ([ "$2" == "boolean" ] && [ "$param_value" != true ] && [ "$param_value" != false ]) || \
           ([ "$2" == "integer" ] && [[ ! "$param_value" =~ ^[-+]?([1-9][[:digit:]]*|1)$ ]]) || \
           ([ "$2" == "string" ] && [ "$param_value" == "" ]) ; then
            echo "Wrong paramater in $CONF_FILE. Using $1=$3" >&2
            param_value=$3
        fi
    fi

    echo $param_value
}

if $(get_property "skipAutosnap" "boolean" "false") ; then
    echo "==> skipping timeshift-autosnap due skipAutosnap in $CONF_FILE set to TRUE." >&2; exit 0;
fi

if $(get_property "skipRsyncAutosnap" "boolean" "false") && ! [ $(findmnt / -no fstype) == "btrfs" ] ; then
    echo "==> skipping timeshift-autosnap due skipRsyncAutosnap in $CONF_FILE set to TRUE." >&2; exit 0;
fi

readonly SNAPSHOT_DESCRIPTION=$(get_property "snapshotDescription" "string" "{timeshift-autosnap} {created before upgrade}")

timeshift --create --comments "$SNAPSHOT_DESCRIPTION" || { echo "Unable to run timeshift-autosnap! Please close Timeshift and try again. Script will now exit..." >&2; exit 1; }

if $(get_property "deleteSnapshots" "boolean" "true") ; then
    timeshift --list > $SNAPSHOTS_TO_DELETE
    sed -ni "/$SNAPSHOT_DESCRIPTION/p" $SNAPSHOTS_TO_DELETE
    sed -ni "s/.*\($SNAPSHOT_NAME_DATE_PATTERN\).*/\1/p" $SNAPSHOTS_TO_DELETE

    count=$(($(sed -n '$=' $SNAPSHOTS_TO_DELETE)-$(get_property "maxSnapshots" "integer" "3")))

    if [ "$count" -gt 0 ] ; then
        sed -i $(($count))q $SNAPSHOTS_TO_DELETE
        
        for snapshot in $(cat $SNAPSHOTS_TO_DELETE); do
            timeshift --delete --snapshot $snapshot
        done
    fi
fi;

if $(get_property "updateGrub" "boolean" "true") && [ "$(pacman -Qs ^grub-btrfs$)" ]; then
    grub-mkconfig -o /boot/grub/grub.cfg
fi;

exit 0
