#!/bin/bash
set -e

# Adastra Storage Uninstaller Script

INSTALL_DIR="/opt/adastra-storage"
SERVICE_USER="adastra"

echo "=========================================="
echo "Adastra Storage Uninstaller"
echo "=========================================="
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root (use sudo)"
    exit 1
fi

# Confirm removal
echo "This will remove Adastra Storage from your system."
echo "Installation directory: $INSTALL_DIR"
read -p "Are you sure you want to continue? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Uninstallation cancelled."
    exit 0
fi

echo ""
echo "Step 1: Stopping and disabling service..."

# Stop and disable service
if systemctl is-active adastra-storage.service >/dev/null 2>&1; then
    echo "Stopping adastra-storage service..."
    systemctl stop adastra-storage.service
fi

if systemctl is-enabled adastra-storage.service >/dev/null 2>&1; then
    echo "Disabling adastra-storage service..."
    systemctl disable adastra-storage.service
fi

systemctl daemon-reload

echo ""
echo "Step 2: Removing systemd service file..."

if [ -f /etc/systemd/system/adastra-storage.service ]; then
    rm -f /etc/systemd/system/adastra-storage.service
    systemctl daemon-reload
fi

echo ""
echo "Step 3: Removing application files..."

# Ask about data preservation
read -p "Do you want to preserve data directory? (Y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Nn]$ ]]; then
    echo "Removing all files including data..."
    rm -rf "$INSTALL_DIR"
else
    echo "Preserving data directory..."
    if [ -d "$INSTALL_DIR/data" ]; then
        echo "Data directory preserved at: $INSTALL_DIR/data"
        # Remove everything except data
        find "$INSTALL_DIR" -mindepth 1 -maxdepth 1 ! -name data -exec rm -rf {} +
    else
        rm -rf "$INSTALL_DIR"
    fi
fi

echo ""
echo "Step 4: Removing service user (optional)..."

read -p "Remove service user '$SERVICE_USER'? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if id "$SERVICE_USER" &>/dev/null; then
        userdel "$SERVICE_USER" 2>/dev/null || true
        echo "Service user removed."
    fi
fi

echo ""
echo "=========================================="
echo "Uninstallation Complete!"
echo "=========================================="
echo ""
echo "Note: System dependencies (golang, zfsutils-linux, etc.)"
echo "      were not removed. Remove them manually if needed:"
echo ""
echo "  apt-get remove golang-go zfsutils-linux smartmontools"
echo "                  nfs-kernel-server samba targetcli-fb"
echo ""

