#!/bin/sh

# cryptsetup-cleanup - Parse /etc/crypttab and close/remove encrypted devices safely
# This script is called on shutdown to clean up device mapper entries

export PATH=/usr/bin:/usr/sbin:/bin:/sbin

set -e

log_info() {
    echo "[INFO] $*" >&2
}

log_error() {
    echo "[ERROR] $*" >&2
}

# Get list of active crypt devices from crypttab
get_crypt_devices() {
    local crypttab="/etc/crypttab"

    if [[ ! -f "$crypttab" ]]; then
        return 0
    fi

    while IFS= read -r line; do
        # Skip comments and empty lines
        [[ "$line" =~ ^[[:space:]]*# ]] && continue
        [[ -z "$line" ]] && continue

        # Extract device name (first field)
        local name
        read -r name _ <<<"$line"
        [[ -n "$name" ]] && echo "$name"
    done < "$crypttab"
}

# Close a device mapper entry
close_device() {
    local name="$1"
    local device="/dev/mapper/$name"

    # Check if it exists
    if [[ ! -e "$device" ]]; then
        return 0
    fi

    # Check if mounted
    if mountpoint -q "$device" 2> /dev/null; then
        log_error "Device $name is still mounted, cannot close"
        return 1
    fi

    log_info "Closing device: $name"
    if cryptsetup close "$name" 2> /dev/null; then
        log_info "Device $name closed successfully"
        return 0
    else
        log_error "Failed to close device $name"
        return 1
    fi
}

main() {
    log_info "Cleaning up encrypted devices"

    local failed=0
    while read -r name; do
        close_device "$name" || failed=$((failed + 1))
    done < <(get_crypt_devices)

    if [[ $failed -gt 0 ]]; then
        log_error "$failed devices failed to close"
        return 1
    fi

    log_info "All encrypted devices closed successfully"
    return 0
}

main "$@"
