#!/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.

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="$(ps -q $(ps -p "$$" -o ppid=) -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
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

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"

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

done

exit 0
