#!/bin/bash

#
# Copyright (C) 2023 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

set -e

rom_part=$(lsblk -l --json | jq -r '.blockdevices[] | select(any(.mountpoints[]; . == "/rom")) | .name')
rom_disk=$(lsblk -lno pkname /dev/$rom_part)

data_part=$(lsblk -l --json | jq -r '.blockdevices[] | select(any(.mountpoints[]; . == "/mnt/data")) | .name')
data_disk=$(lsblk -lno pkname /dev/$data_part)

# Removing auto-mount
uci delete fstab.ns_data
uci commit fstab

# Configuring rsyslog
uci delete rsyslog.ns_data
uci commit rsyslog
/etc/init.d/rsyslog restart

# Removing sync-data cron job
crontab -l | grep -v "/usr/sbin/sync-data" | sort | uniq | crontab -
/etc/init.d/cron restart

# Stop process that will prevent umount
/etc/init.d/dnsmasq stop
/etc/init.d/victoria-metrics stop
/etc/init.d/victoria-logs stop 2>/dev/null || :
# Sync and wait for the disk to be free
sync && sleep 5

# Umounting data device
umount -f /mnt/data
rm -rf /mnt/data

# Removing parition
if [ "$rom_disk" == "$data_disk" ]; then
    parted "/dev/${data_disk}" rm 3
fi

# Restore dnsmasq to /tmp before the storage disappears.
/usr/libexec/ns-storage-dhcp-leases

# Start services
/etc/init.d/dnsmasq start
/etc/init.d/victoria-metrics start
/etc/init.d/victoria-logs start 2>/dev/null || :
