#!/usr/bin/env bash
# vim:et:ts=2:sts=2:sw=2

# Get absolute repository root (especially when symlinked)
ROOT="$(realpath "$(dirname "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")")")"

# Load accompanying bash library
source "$ROOT/lib/lib.bash"

# Exit now unless run as root
assert-is-root

BTRFS="${1:-"/var/btrfs"}" # Path to system BTRFS root

if [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  [$(c btrfs-path)]

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") creates a new snapshot of the guest session
    for a TechLit system hosted in BTRFS volume at $(c btrfs-path)
                                        (default: $(c /var/btrfs))
"
  exit 1
fi

if [ -r "/tmp/tl-did-restore" ]; then
  err ""
  err "An image restored during this boot."
  err "Reboot before chaning the guest session."
  err ""
  exit 1
fi

say "This script will need root access via $(c sudo)"
sudo echo thank you

say "Turning WiFi on"
sudo nmcli r wifi on

say "Setting volume to 70%"
sudo su guest -c 'pactl -s /run/user/2000/pulse/native set-sink-volume @DEFAULT_SINK@ 70%'

# TODO: look for more
say "Cleaning up guest states"
{
  run rm -rf "$BTRFS/@guest/.config/cinnamon-session/saved-session"/* || :
  # TODO: how does this affect the volume setting above?
  run rm -rf "$BTRFS/@guest/.config/pulse" || :
  run rm -rf "$BTRFS/@guest/.dbus/session-bus" || :
}

files_to_remove=(
  .bash_history
  .vim
  .viminfo
  .lesshst
  .npm
  .bundle
  .irb_history
  .python_history
)
say "Removing files: $files_to_remove"
for file in "${files_to_remove[@]}"; do
  run rm -rf "$BTRFS/@root/home/guest/$file"
done

say "Creating new read-write snapshot"; {
    if [ -d "$BTRFS/@guest.prev" ]; then
      run sudo btrfs subvol delete "$BTRFS/@guest.prev"
    fi
    if [ -d "$BTRFS/@guest" ]; then
      run sudo mv "$BTRFS/@guest"{,.prev}
    fi
    run sudo btrfs subvol snap "$BTRFS/@root/home/guest" "$BTRFS/@guest"
}

say "Done."
