#!/usr/bin/env bash
# ============================================================================
# Knotsday - Migrate Bitcoin Data from exFAT/NTFS to ext4
#
# If your blockchain is on an exFAT or NTFS drive, this script helps migrate
# it to ext4 safely. It stages data to a temporary location, reformats the
# drive, and copies everything back.
#
# Usage:
#   ./migrate-to-ext4.sh
#
# Requirements:
#   - Enough free space on another drive to stage the blockchain data
#   - The Bitcoin node must be stopped before running
# ============================================================================

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
GOLD='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info()  { echo -e "${BLUE}[INFO]${NC} $*"; }
ok()    { echo -e "${GREEN}[OK]${NC} $*"; }
warn()  { echo -e "${GOLD}[WARN]${NC} $*"; }
err()   { echo -e "${RED}[ERROR]${NC} $*" >&2; }

echo ""
echo "  ================================================"
echo "    Knotsday - Migrate to ext4"
echo "  ================================================"
echo ""

# Check node is stopped
if pgrep -x bitcoind >/dev/null 2>&1 || pgrep -x bitcoin-qt >/dev/null 2>&1; then
    err "Bitcoin node is still running. Stop it first:"
    echo "  bitcoin-cli stop"
    exit 1
fi

echo "This script will:"
echo "  1. Copy blockchain data to a staging location"
echo "  2. Reformat your drive as ext4"
echo "  3. Copy data back"
echo "  4. Update bitcoin.conf"
echo ""
warn "The node must be stopped before proceeding."
echo ""

# --- Gather info ---
read -rp "$(echo -e "${GOLD}Current blockchain data directory: ${NC}")" SOURCE_DIR
if [[ ! -d "${SOURCE_DIR}" ]]; then
    err "Directory does not exist: ${SOURCE_DIR}"
    exit 1
fi

DATA_SIZE=$(du -sh "${SOURCE_DIR}" | awk '{print $1}')
info "Data size: ${DATA_SIZE}"

read -rp "$(echo -e "${GOLD}Staging directory (must have enough free space): ${NC}")" STAGING_DIR

STAGING_FREE=$(df -h "$(dirname "${STAGING_DIR}")" | tail -1 | awk '{print $4}')
info "Free space at staging location: ${STAGING_FREE}"

read -rp "$(echo -e "${GOLD}Device to reformat (e.g. /dev/sdb): ${NC}")" TARGET_DEVICE
read -rp "$(echo -e "${GOLD}Partition to format (e.g. /dev/sdb1, or leave blank for whole disk): ${NC}")" TARGET_PARTITION

echo ""
warn "This will:"
echo "  - Copy ${DATA_SIZE} from ${SOURCE_DIR} to ${STAGING_DIR}"
echo "  - Reformat ${TARGET_PARTITION:-${TARGET_DEVICE}} as ext4"
echo "  - Copy data back"
echo ""

read -rp "$(echo -e "${RED}Type 'MIGRATE' to proceed: ${NC}")" answer
if [[ "${answer}" != "MIGRATE" ]]; then
    echo "Aborted."
    exit 0
fi

# --- Step 1: Stage ---
info "Copying data to staging..."
mkdir -p "${STAGING_DIR}"
rsync -ah --progress "${SOURCE_DIR}/" "${STAGING_DIR}/"
ok "Data staged."

# --- Step 2: Reformat ---
info "Unmounting..."
sudo umount "${TARGET_PARTITION:-${TARGET_DEVICE}}1" 2>/dev/null || true

if [[ -z "${TARGET_PARTITION}" ]]; then
    info "Creating partition table..."
    sudo parted -s "${TARGET_DEVICE}" mklabel gpt
    sudo parted -s "${TARGET_DEVICE}" mkpart primary ext4 0% 100%
    sleep 1
    TARGET_PARTITION="/dev/$(lsblk -ln -o NAME "${TARGET_DEVICE}" | tail -1)"
fi

info "Formatting ${TARGET_PARTITION} as ext4..."
sudo mkfs.ext4 -L bitcoin "${TARGET_PARTITION}"

# --- Step 3: Mount and restore ---
MOUNT_POINT="/media/${USER}/bitcoin"
sudo mkdir -p "${MOUNT_POINT}"
sudo mount "${TARGET_PARTITION}" "${MOUNT_POINT}"
sudo chown "${USER}:${USER}" "${MOUNT_POINT}"

info "Copying data back..."
rsync -ah --progress "${STAGING_DIR}/" "${MOUNT_POINT}/.bitcoin/"
ok "Data restored."

# --- Step 4: fstab ---
UUID=$(sudo blkid -s UUID -o value "${TARGET_PARTITION}")
if ! grep -q "${UUID}" /etc/fstab 2>/dev/null; then
    echo "UUID=${UUID} ${MOUNT_POINT} ext4 defaults,noatime 0 2" | sudo tee -a /etc/fstab
    ok "Added to /etc/fstab"
fi

# --- Step 5: Update bitcoin.conf ---
BITCOIN_CONF="${HOME}/.bitcoin/bitcoin.conf"
if [[ -f "${BITCOIN_CONF}" ]]; then
    info "Updating datadir in bitcoin.conf..."
    sed -i "s|^datadir=.*|datadir=${MOUNT_POINT}/.bitcoin|" "${BITCOIN_CONF}"
    ok "bitcoin.conf updated."
fi

echo ""
ok "Migration complete."
echo ""
echo "  New data directory: ${MOUNT_POINT}/.bitcoin"
echo "  Filesystem: ext4"
echo ""
echo "Start the node with reindex to rebuild indexes:"
echo "  bitcoin-qt -reindex &"
echo ""
echo "You can delete the staging data once the reindex completes:"
echo "  rm -rf ${STAGING_DIR}"
