#!/usr/bin/env bash
# Generic btrfsmaintenance install script
# Copyright 2021-2025 Bryan C. Roessler
# Licensed under the Apache License, Version 2.0
p="${BASH_SOURCE[0]%/*}"; [[ -r $p/script-functions ]] && . "$p"/script-functions || exit 1

is_root

# Optionally provide the config directory manually
if [[ $# -lt 1 ]]; then
    if [[ -d /etc/sysconfig ]]; then
        CONFDIR=/etc/sysconfig
    elif [[ -d /etc/default ]]; then
        CONFDIR=/etc/default
    else
        echo "Cannot detect sysconfig directory, please specify manually"
        exit 1
    fi
else
    CONFDIR="$1"
fi

# This is hardcoded by the btrfs maintenance scripts, change at your peril
INSTALLDIR="/usr/share/btrfsmaintenance"

# Backup existing installation
if [[ -d "$INSTALLDIR" ]]; then
    TEMPDIR="/tmp/btrfs-maintenance.bk"
    echo "Moving existing $INSTALLDIR to $TEMPDIR"
    [[ -d "$TEMPDIR" ]] && rm -rf "$TEMPDIR"
    mv "$INSTALLDIR" "$TEMPDIR"
fi

git clone "https://github.com/kdave/btrfsmaintenance.git" "$INSTALLDIR"

# Quirks
if [[ -e "/etc/os-release" ]]; then
    source "/etc/os-release"
    if [[ "$ID" == "centos" && "$VERSION_ID" == "7" ]]; then
        sed -i 's/flock --verbose/flock' "$INSTALLDIR"/btrfsmaintenance-functions
    fi
fi

chmod 755 "$INSTALLDIR"/*.sh

# Copy config file
[[ ! -f "$CONFDIR"/btrfsmaintenance ]] && install -oroot -groot -m644 "$INSTALLDIR"/sysconfig.btrfsmaintenance "$CONFDIR"/btrfsmaintenance

# Copy systemd files and reload
for f in "$INSTALLDIR"/btrfs-*.{service,timer}; do
    cp "$f" /usr/lib/systemd/system/
done
systemctl daemon-reload

# Optionally, start and enable the services
# systemctl enable --now btrfs-scrub
