#!/bin/bash

mkinitcpio_has_grub_btrfs_overlayfs_hook() {
    grep -qe "^HOOKS=.*grub-btrfs-overlayfs" /etc/mkinitcpio.conf
}

post_install() {
    # Change grub snapshot submenu name
    if [ -e /etc/lsb-release ]; then
       echo "Using default grub snapshot submenu name"
    else
       sed -i /etc/default/grub-btrfs/config \
           -e "s,.*GRUB_BTRFS_SUBMENUNAME=.*,GRUB_BTRFS_SUBMENUNAME=\"$(sed '/^NAME=/!d;s/NAME=//;s/"//gm' /etc/os-release) snapshots\","
       echo "Generating grub snapshot submenu name from /etc/os-release values"
    fi

    if [[ $(/usr/bin/systemctl is-enabled grub-btrfs.path) == "enabled" ]]; then 
        /usr/bin/systemctl disable --now grub-btrfs.path; 
    fi

    echo "Enabling automatic rebuild of grub-btrfs when snapshots are taken"
    /usr/bin/systemctl daemon-reload
    /usr/bin/systemctl enable --now grub-btrfs-snapper.path
    /usr/bin/systemctl enable --now snapper-cleanup.timer
    
    if ! mkinitcpio_has_grub_btrfs_overlayfs_hook; then
        sed -re 's/(^HOOKS=[\"|(][^")]+)/\1 grub-btrfs-overlayfs/gi' -i /etc/mkinitcpio.conf
    fi
}

pre_remove() {
    if mkinitcpio_has_grub_btrfs_overlayfs_hook; then
        sed -re 's/(^HOOKS=["(].*) grub-btrfs-overlayfs/\1/g' -i /etc/mkinitcpio.conf
    fi
    echo "Disabling related snapper and grub-btrfs services"
    /usr/bin/systemctl disable --now grub-btrfs-snapper.path
    /usr/bin/systemctl disable --now snapper-cleanup.timer
}
