#!/bin/bash

# snap-pac
# https://github.com/wesbarnett/snap-pac
# Copyright (C) 2016, 2017 James W. Barnett

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Main script.

declare -r SNAPPER_CONFIG_FILE=/etc/conf.d/snapper
declare -r DESC_LIMIT=48
declare -r name="snap-pac"
declare PACMAN_ABORT_ON_FAIL="no"
declare -r pacman_cmd="$(sed 's./usr/bin/pacman.pacman.g' <(ps -C pacman -o args=))"
declare -i x=0
declare -r pre_or_post=$1

out() { printf "$1 $2\n" "${@:3}"; }
error() { out "==> \033[00;31mERROR:\033[00m" "$@"; } >&2
warning() { out "==> \033[00;33mWARNING:\033[00m" "$@"; } >&2
die() { 
    error "$@"
    [[ $PACMAN_ABORT_ON_FAIL == "no" ]] && exit 0
    exit 1
}
error_exit() { die "Aborted due to error."; }
kill_exit() { die "\nExited due to user intervention."; }

truncate_description() {
    desc="$@"
    if [[ "${#desc}" -gt $DESC_LIMIT ]]; then 
        echo "$(echo $desc | cut -c 1-$DESC_LIMIT)..."
    else
        echo $desc
    fi
}

set_defaults() {
    PACMAN_PRE_POST="no"
    [[ $CONFIG == "root" ]] && PACMAN_PRE_POST="yes"
    PACMAN_PRE_DESCRIPTION="$pacman_cmd"
    PACMAN_POST_DESCRIPTION="$pacman_cmd"
    PACMAN_CLEANUP_ALGORITHM="number"
}

trap error_exit ERR
trap kill_exit SIGTERM SIGINT

[[ -z "$pacman_cmd" ]] && die "snap-pac should only be called via provided pacman hooks."
[[ ! -d /var/run/dbus ]] && die "No dbus available. Are you in a chroot environment?"

source "$SNAPPER_CONFIG_FILE"

for CONFIG in $SNAPPER_CONFIGS; do

    set_defaults
    source /etc/snapper/configs/"$CONFIG"

    [[ $PACMAN_PRE_POST == "no" ]] && continue

    prefile="/tmp/$name-pre_$CONFIG"
    snapper_cmd="snapper --config $CONFIG create --type $pre_or_post --cleanup-algorithm $PACMAN_CLEANUP_ALGORITHM --print-number --description"

    x=$((x+1))

    if [[ "$pre_or_post" == "pre" ]]; then
        printf "==> %s: $($snapper_cmd "$(truncate_description $PACMAN_PRE_DESCRIPTION)" | tee "$prefile")\n" "$CONFIG"
    elif [[ -f $prefile && "$pre_or_post" == "post" ]]; then
        printf "==> %s: $($snapper_cmd "$(truncate_description $PACMAN_POST_DESCRIPTION)" --pre-number "$(< "$prefile")")\n" "$CONFIG"
        rm -f "$prefile"
    fi

done

[[ $x -eq 0 ]] && die "No snapper configurations are set up for snapshots to be taken."

exit 0
