#!/usr/bin/sh
#
# Hybrid Appliance RAID maintenance tool
#
# Copyright (C) 2026 Skyhigh Security
#

if [ "$(id -u)" -ne 0 ]; then
    exec sudo -n -- "$0" "$@"
fi

LOG_FILE="/var/log/hyb-raid.log"

[ -e "$LOG_FILE" ] || : > "$LOG_FILE"
chmod 0600 "$LOG_FILE" 2>/dev/null || true

log_info() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

sanitize_user_message() {
    echo "$1" | sed -E 's#/dev/[[:alnum:]_.-]+#<device>#g; s#\b(sd|vd|hd)[a-z][0-9]*\b#<disk>#g; s#\bnvme[0-9]+n[0-9]+p?[0-9]*\b#<disk>#g'
}

raid_usage() {
    echo "usage: hyb-raid <command> [option]"
    echo ""
    echo "    commands:"
    echo "        add <dev>           - add dev to raid volumes"
    echo "        info                - show raid devices and status"
    echo "        list                - show raid devices and status"
    echo "        locate <dev>        - enable locate led for dev"
    echo "        locate-off <dev>    - disable locate led for dev"
    echo "        remove <dev>        - remove dev from all raid volumes"
    echo "        grub <dev1> <dev2>  - repair GRUB on a RAID disk"
}

raid_main() {
    local command="$1"
    local arg1="$2"
    local arg2="$3"
    local product

    if [ -z "$command" ] ; then
        raid_usage
        exit 1
    fi

    case "$command" in
        help|-h|--help)
            raid_usage
            exit 0
            ;;
    esac

    product=$(dmidecode -s system-product-name 2>/dev/null)
    case "$product" in
        "Appliance D1"|"Appliance D2"|"Appliance D3"*|"Appliance F1"|"Appliance F2")
            ;;
        *)
            err "Installed platform ($product) does not support hyb-raid"
            ;;
    esac

    # Strip /dev/ prefix so both 'sda' and '/dev/sda' are accepted
    arg1="${arg1#/dev/}"
    arg2="${arg2#/dev/}"

    if [ -z "$(ls -d /sys/block/md* 2>/dev/null)" ] ; then
        err "no supported raid devices found"
    fi

    case "$command" in
        add)
            [ -n "$arg1" ] || { raid_usage; exit 1; }
            raid_add "$arg1"
            ;;
        info|list)
            raid_list
            ;;
        locate)
            [ -n "$arg1" ] || { raid_usage; exit 1; }
            raid_locate "$arg1"
            ;;
        locate-off)
            [ -n "$arg1" ] || { raid_usage; exit 1; }
            raid_locate_off "$arg1"
            ;;
        remove)
            [ -n "$arg1" ] || { raid_usage; exit 1; }
            raid_remove "$arg1"
            ;;
        grub)
            [ -n "$arg1" ] && [ -n "$arg2" ] || { raid_usage; exit 1; }
            raid_validate_device "$arg1"
            raid_validate_device "$arg2"
            raid_install_grub "$arg1" "$arg2"
            ;;
        *)
            raid_usage
            exit 1
            ;;
    esac
}

err() {
    local message="$*"
    local user_message
    user_message=$(sanitize_user_message "$message")
    log_info "ERROR: $user_message"
    echo "error: $message" 1>&2
    exit 1
}

warn() {
    local message="$*"
    local user_message
    user_message=$(sanitize_user_message "$message")
    log_info "WARNING: $user_message"
    echo "warning: $message" 1>&2
}

run() {
    local status
    [ -n "$DEBUG" ] && echo "*** $*"
    LIBC_FATAL_STDERR_=1 MALLOC_CHECK_=3 "$@"
    status=$?
    [ $status -eq 0 ] || err "$* failed with $status"
}

runx() {
    local status
    [ -n "$DEBUG" ] && echo "*** $*"
    LIBC_FATAL_STDERR_=1 MALLOC_CHECK_=3 "$@" >/dev/null 2>&1
    status=$?
    [ $status -eq 0 ] || err "$* failed with status $status"
}

raid_validate_device() {
    local dev="$1"
    if ! echo "$dev" | egrep -q '^(sd|vd|hd)[a-z]$' ; then
        err "invalid device name ($dev) - expected disk name only, e.g. 'sda' not '/dev/sda' or 'sda1'"
    fi
    [ -d "/sys/block/$dev" ] || err "non-existent device ($dev)"
    [ -b "/dev/$dev" ] || err "non-existent device node ($dev)"
}

raid_validate_partition() {
    local dev="$1"
    if ! echo "$dev" | egrep -q '^(sd|vd|hd)[a-z][0-9]+$' ; then
        err "invalid device name ($dev)"
    fi
    [ -n "$(ls -d /sys/block/*/$dev 2>/dev/null)" ] || err "non-existent device ($dev)"
}

raid_find_parent() {
    local part="$1"
    local sys parent
    raid_validate_partition "$part"
    sys="$(ls -d /sys/block/*/$part 2>/dev/null)"
    parent="$(echo "$sys" | tr '/' '\n' | tail -n 2 | head -n 1)"
    [ -n "$parent" ] || err "could not find parent device for partition ($part)"
    echo "$parent"
}

raid_clone_partitions() {
    local currentdev="$1"
    local newdev="$2"
    local labeltype table part start size end partinfo partflag parttype partnum
    local espflag esp

    labeltype=$(/usr/sbin/parted -ms -- /dev/$currentdev print | grep "^/dev/$currentdev" | cut -d: -f6)

    table=""
    partnum=1
    for part in $(ls -d /sys/block/$currentdev/${currentdev}[0-9]* 2>/dev/null); do
        start=$(cat "$part/start")
        size=$(cat "$part/size")
        partinfo=$(/usr/sbin/parted -ms -- /dev/$currentdev print | grep "^$partnum:")
        parttype=$(echo "$partinfo" | cut -d: -f5)
        partflag=$(echo "$partinfo" | cut -d: -f7 | cut -d';' -f1)
        [ "$partflag" = "boot, esp" ] && partflag="boot"
        table="$table $start:$size:$parttype:$partflag"
        [ -n "$DEBUG" ] && echo "raid_clone_partitions: [$partnum] start=$start size=$size"
        partnum=$((partnum + 1))
    done

    echo "Cloning the partitions on new disk."
    case "$labeltype" in
        gpt)   run /usr/sbin/parted --script -- /dev/$newdev "mklabel gpt" ;;
        msdos) run /usr/sbin/parted --script -- /dev/$newdev "mklabel msdos" ;;
        *)     err "unknown disklabel type $labeltype" ;;
    esac

    run /usr/sbin/udevadm settle

    partnum=1
    espflag=0
    for part in $table; do
        start=$(echo "$part" | cut -d: -f1)
        size=$(echo "$part" | cut -d: -f2)
        parttype=$(echo "$part" | cut -d: -f3)
        partflag=$(echo "$part" | cut -d: -f4)
        end=$((start + size - 1))

        case "$parttype" in
            fat16|fat32)
                run /usr/sbin/parted --script -- /dev/$newdev "unit s mkpart ESP $parttype $start $end"
                espflag=1
                ;;
            ext2|ext3|ext4)
                run /usr/sbin/parted --script -- /dev/$newdev "unit s mkpart primary $parttype $start $end"
                ;;
            *)
                run /usr/sbin/parted --script -- /dev/$newdev "unit s mkpart primary ext2 $start $end"
                ;;
        esac

        case "$partflag" in
            raid|lvm|boot)
                run /usr/sbin/parted --script -- /dev/$newdev "set $partnum $partflag on"
                ;;
        esac
        partnum=$((partnum + 1))
    done

    run /usr/sbin/udevadm settle

    if [ "$espflag" = "1" ] ; then
        esp=/dev/${newdev}1
        runx mkfs.fat -F32 "$esp"
    fi

    [ -n "$DEBUG" ] && echo "raid_clone_partitions: success"
}

raid_detect_efi_loader() {
    local disk="$1"
    local esp_part
    local mount_point loader_path

    case "$disk" in
        nvme*) esp_part="/dev/${disk}p1" ;;
        *)     esp_part="/dev/${disk}1" ;;
    esac

    [ -b "$esp_part" ] || return 1

    mount_point=$(mktemp -d /tmp/hyb-raid-efi.XXXXXX) || return 1

    if mount -o ro "$esp_part" "$mount_point" >/dev/null 2>&1; then
        if [ -f "$mount_point/EFI/slos/grubx64.efi" ]; then
            loader_path='\EFI\slos\grubx64.efi'
        elif [ -f "$mount_point/EFI/SkyhighSecurity_Linux/grubx64.efi" ]; then
            loader_path='\EFI\SkyhighSecurity_Linux\grubx64.efi'
        elif [ -f "$mount_point/EFI/BOOT/BOOTX64.EFI" ]; then
            loader_path='\EFI\BOOT\BOOTX64.EFI'
        fi
        umount "$mount_point" >/dev/null 2>&1 || true
    fi

    rm -rf "$mount_point" >/dev/null 2>&1 || true

    [ -n "$loader_path" ] || return 1
    echo "$loader_path"
    return 0
}

raid_install_grub() {
    local currentdev="$1"
    local newdev="$2"
    local num label bootnum count filepath dev loader_path

    if [ -d /sys/firmware/efi ] ; then
        loader_path=$(raid_detect_efi_loader "$newdev") || loader_path=""
        [ -n "$loader_path" ] || loader_path=$(raid_detect_efi_loader "$currentdev") || loader_path=""
        [ -n "$loader_path" ] || loader_path='\EFI\slos\grubx64.efi'
        log_info "Using EFI loader path: $loader_path"

        echo "Installing grub to new disk's ESP"
        filepath="/etc/kernel/postinst.d/99-hyb-multi-esp-grub-update.sh"
        if [ -f "$filepath" ] ; then
            runx "$filepath" "$currentdev" "$newdev"
        else
            esp_mount=$(mktemp -d /tmp/hyb-raid-grub.XXXXXX) || \
                err "failed to create temporary mount point for new disk ESP"
            mount "/dev/${newdev}1" "$esp_mount" >/dev/null 2>&1 || {
                rmdir "$esp_mount" >/dev/null 2>&1 || true
                err "failed to mount new disk ESP for GRUB installation"
            }
            if command -v grub2-install >/dev/null 2>&1 ; then
                runx grub2-install --target=x86_64-efi \
                    --efi-directory="$esp_mount" \
                    --bootloader-id=SkyhighSecurity_Linux \
                    --no-nvram --removable
            else
                umount "$esp_mount" >/dev/null 2>&1 || true
                rmdir "$esp_mount" >/dev/null 2>&1 || true
                err "GRUB installation failed: grub2-install is not available"
            fi
            umount "$esp_mount" >/dev/null 2>&1 || \
                err "failed to unmount new disk ESP after GRUB installation"
            rmdir "$esp_mount" >/dev/null 2>&1 || true
        fi

        runx /usr/bin/sync
    else
        runx /usr/sbin/update-grub
        runx /usr/bin/sync
        runx /usr/sbin/grub2-install /dev/$newdev
    fi
}

raid_add() {
    local newdev="$1"
    local currentdev parent slave raid n

    raid_validate_device "$newdev"

    for raid in $(ls -d /sys/block/md* 2>/dev/null); do
        for slave in $(ls -d "$raid"/slaves/* 2>/dev/null); do
            parent="$(raid_find_parent "$(basename "$slave")")"
            if [ "$parent" = "$newdev" ] ; then
                err "device $(basename "$slave") is already member of $(basename "$raid")"
            fi
        done
    done

    for raid in $(ls -d /sys/block/md* 2>/dev/null); do
        n="$(ls -d "$raid"/slaves/* 2>/dev/null | wc -l)"
        if [ "$n" -gt 1 ] ; then
            err "raid add needs manual intervention ($n members for $(basename "$raid"))"
        fi
    done

    currentdev=""
    for raid in $(ls -d /sys/block/md* 2>/dev/null); do
        for slave in $(ls -d "$raid"/slaves/* 2>/dev/null); do
            parent="$(raid_find_parent "$(basename "$slave")")"
            if [ -n "$currentdev" ] ; then
                [ "$currentdev" = "$parent" ] || err "raid add needs manual intervention (differing members)"
            else
                currentdev="$parent"
            fi
        done
    done

    raid_validate_device "$currentdev"
    [ "$(cat /sys/block/$newdev/size)" = "$(cat /sys/block/$currentdev/size)" ] || err "size does not match for $currentdev and $newdev"

    raid_clone_partitions "$currentdev" "$newdev"
    raid_install_grub "$currentdev" "$newdev"

    for raid in $(ls -d /sys/block/md* 2>/dev/null); do
        for slave in $(ls -d "$raid"/slaves/* 2>/dev/null); do
            runx /usr/sbin/mdadm --zero-superblock --force "/dev/${newdev}$(cat "$slave/partition")"
            run /usr/sbin/mdadm "/dev/$(basename "$raid")" --add-spare "/dev/${newdev}$(cat "$slave/partition")"
        done
    done
}

raid_list() {
    local base dev level state completed degraded action slot path lower
    local sync_completed

    base="/sys/devices/virtual/block"
    for path in $(ls -d "$base"/*/md 2>/dev/null | sort -t/ -k6.3n); do
        dev=$(basename "$(dirname "$path")")
        level=$(cat "$base/$dev/md/level" 2>/dev/null)
        state=$(cat "$base/$dev/md/array_state" 2>/dev/null)

        if [ "$state" = "inactive" ] ; then
            [ -n "$level" ] || level="none"
            printf "%-6s %-6s %-10s\n" "$dev" "$level" "inactive"
            continue
        fi

        sync_completed=$(cat "$base/$dev/md/sync_completed" 2>/dev/null)
        completed=$(printf '%s\n' "$sync_completed" | awk '
            function isnum(value) { return value ~ /^[0-9]+$/ }
            {
                if (NF >= 3 && isnum($1) && isnum($3) && $3 > 0) {
                    printf "%d", ($1 * 100) / $3
                    exit
                }
                if (isnum($1)) {
                    print $1
                    exit
                }
                print 0
            }
        ')
        degraded=$(cat "$base/$dev/md/degraded" 2>/dev/null)
        action=$(cat "$base/$dev/md/sync_action" 2>/dev/null)

        printf "%-6s %-6s " "$dev" "$level"
        if [ "$action" = "resync" ] || [ "$action" = "recover" ] ; then
            printf "%-10s\n" "rebuild $completed%"
        elif [ "$degraded" = "1" ] ; then
            printf "%-10s\n" "degraded"
        else
            printf "%-10s\n" "$state"
        fi

        for lower in $(ls -d "$base/$dev"/md/dev-* 2>/dev/null); do
            slot=$(cat "$lower/slot" 2>/dev/null)
            [ "$slot" = "none" ] && slot="-"
            printf "%-6s %-6s\n" "$dev:$slot" "$(basename "$lower" | cut -d- -f2)"
        done
    done
}

raid_locate() {
    local dev="$1"
    local output
    local status
    local filtered_output
    [ -x /usr/sbin/ledctl ] || err "ledctl not found - install the ledmon package"
    raid_validate_device "$dev"
    output=$(/usr/sbin/ledctl -x locate=/dev/$dev 2>&1)
    status=$?
    filtered_output=$(echo "$output" | grep -Ev '^/dev/shm/ledmon\.conf: does not exist, using global config file$|^/etc/ledmon\.conf: does not exist, using built-in defaults$')
    [ -n "$filtered_output" ] && log_info "ledctl locate output: $filtered_output"
    [ $status -eq 0 ] || err "failed to enable locate LED for $dev"
    echo "Locate LED command completed."
}

raid_locate_off() {
    local dev="$1"
    local output
    local status
    local filtered_output
    [ -x /usr/sbin/ledctl ] || err "ledctl not found - install the ledmon package"
    raid_validate_device "$dev"
    output=$(/usr/sbin/ledctl -x normal=/dev/$dev 2>&1)
    status=$?
    filtered_output=$(echo "$output" | grep -Ev '^/dev/shm/ledmon\.conf: does not exist, using global config file$|^/etc/ledmon\.conf: does not exist, using built-in defaults$')
    [ -n "$filtered_output" ] && log_info "ledctl normal output: $filtered_output"
    [ $status -eq 0 ] || err "failed to disable locate LED for $dev"
    echo "Locate LED disable command completed."
}

raid_remove() {
    local disk="$1" sub dev vol md slave s count

    raid_validate_device "$disk"

    for md in $(ls -d /sys/devices/virtual/block/md* 2>/dev/null); do
        [ "$(cat "$md/md/degraded" 2>/dev/null)" = "0" ] || err "skipping removal of $disk as RAID $(basename "$md") is degraded"
        if [ "$(cat "$md/md/sync_action" 2>/dev/null)" = "resync" ] || [ "$(cat "$md/md/sync_action" 2>/dev/null)" = "recover" ] ; then
            err "skipping removal of $disk as RAID $(basename "$md") is rebuilding"
        fi
    done

    sub=""
    for md in $(ls -d /sys/devices/virtual/block/md* 2>/dev/null); do
        for slave in $(ls -d "$md"/slaves/* 2>/dev/null); do
            dev="$(basename "$slave")"
            vol="$(basename "$md")"
            if [ -d "/sys/block/$disk/$dev" ] ; then
                sub="$sub $vol:$dev"
            fi
        done
    done

    [ -n "$sub" ] || err "device $disk is not a member of any raid"

    count=0
    for s in $sub; do
        vol=$(echo "$s" | cut -d: -f1)
        dev=$(echo "$s" | cut -d: -f2)
        run /usr/sbin/mdadm --fail "/dev/$vol" "/dev/$dev"
        run /usr/sbin/mdadm --remove "/dev/$vol" "/dev/$dev"
        runx /usr/sbin/mdadm --zero-superblock --force "/dev/$dev"
        count=$((count + 1))
    done

    run /usr/bin/dd if=/dev/zero of=/dev/$disk bs=512 count=1 status=none
    run /sbin/blockdev --flushbufs /dev/$disk
    run /usr/sbin/udevadm settle
    run /sbin/blockdev --rereadpt /dev/$disk
}

raid_main "$@"
