#!/bin/sh

SNAPPER_CONFIGS_FILE="/etc/snapper/snapper"
SNAPPER_CONFIG_APK_SNAP_ITEM="root-apk-snap"
DEFAULT_APK_SNAPPER_CONFIG="/etc/apk-snap/default-snapper-config-apk-snap.conf"

# Check if /etc/snapper/snapper exists, add call to config for apk-snap
if [ -f "$SNAPPER_CONFIGS_FILE" ]; then
    # Extract the value of SNAPPER_CONFIGS from the file
    SNAPPER_CONFIGS=$(awk -F'[:"]+' '/^SNAPPER_CONFIGS=/ {print $3}' "$SNAPPER_CONFIGS_FILE")

    # Check if "root-apk-snap" is in the SNAPPER_CONFIGS
    if [ -n "$SNAPPER_CONFIGS" ] && echo "$SNAPPER_CONFIGS" | grep -qw "$SNAPPER_CONFIG_APK_SNAP_ITEM"; then
        :
    else
        # Add "root-apk-snap" to SNAPPER_CONFIGS
        SNAPPER_CONFIGS="$SNAPPER_CONFIGS $SNAPPER_CONFIG_APK_SNAP_ITEM"
        sed -i "/^SNAPPER_CONFIGS=/s/=.*/=\"$SNAPPER_CONFIGS\"/" "$SNAPPER_CONFIGS_FILE"
        echo "$SNAPPER_CONFIG_APK_SNAP_ITEM added to $SNAPPER_CONFIGS_FILE"
    fi
else
    echo "Snapper not properly installed, $SNAPPER_CONFIGS_FILE does not exist"
    exit 1
fi


# Check if snapper config for apk-snap, and snapshots subvol exists; and take appropriate action
if [ -f "/etc/snapper/configs/root-apk-snap" ]  && [ -d "/.snapshots" ]; then
    echo "Snapper config for apk-snap exists, ./snapshots subvol exists."

elif [ -f "/etc/snapper/configs/root-apk-snap" ] && [ ! -d "/.snapshots" ]; then
    echo "Snapper config for apk-snap exists, ./snapshots subvol does not exist."
    echo "Creating /.snapshots subvol"
    btrfs subvol create /.snapshots

elif [ -f "/etc/snapper/configs/root-apk-snap" ] || [ -d "/.snapshots" ]; then
    echo "Snapper config for apk-snap does not exist, snapshots subvol exists."
    echo "Creating snapper config for apk-snap"
    install -Dm 644 $DEFAULT_APK_SNAPPER_CONFIG /etc/snapper/configs/$SNAPPER_CONFIG_APK_SNAP_ITEM

elif [ -f "/etc/snapper/configs/root-apk-snap" ] || [ ! -d "/.snapshots" ]; then
    echo "Snapper config for apk-snap does not exist, snapshots subvol does not exist."
    echo "Creating /.snapshots subvol and snapper config for apk-snap"
    btrfs subvol create /.snapshots
    install -Dm 644 $DEFAULT_APK_SNAPPER_CONFIG /etc/snapper/configs/$SNAPPER_CONFIG_APK_SNAP_ITEM
fi
