# SPDX-License-Identifier: Apache-2.0
# Pure command-line parsing shared with the host policy regression.
partuuid_device() {
    case $1 in PARTUUID=*) partuuid_identity=${1#PARTUUID=} ;; *) return 1 ;; esac
    case $partuuid_identity in ''|*[!0-9A-Fa-f-]*) return 1 ;; esac
    partuuid_identity=$(printf '%s' "$partuuid_identity" | tr 'A-F' 'a-f') || return 1
    printf '/dev/disk/by-partuuid/%s\n' "$partuuid_identity"
}

parse_cmdline() {
    root= rootfstype= rootflags= mode= final_init=/sbin/init root_access=rw
    set -f
    for argument in $1; do
        case $argument in
            root=*) root=${argument#root=} ;;
            rootfstype=*) rootfstype=${argument#rootfstype=} ;;
            rootflags=*) rootflags=${argument#rootflags=} ;;
            init=*) final_init=${argument#init=} ;;
            mode=*) mode=${argument#mode=} ;;
            ro|rw) root_access=$argument ;;
        esac
    done
    set +f
    case $final_init in /*) ;; *) return 1 ;; esac
    case $mode in installer|live) root=/dev/ram0 ;; esac
    case $root in '"'*'"') root=${root#\"}; root=${root%\"} ;; esac
    case $root in /dev/*|PARTUUID=*|UUID=*|LABEL=*) ;;
        *) return 1 ;;
    esac
    case $root in *'"'*|*' '*|*'\'*|*'..'*) return 1 ;; esac
    return 0
}

# Parse data only. The selected PARTUUID, when supplied by GRUB, must own the
# per-installation /boot view; a copied fstab cannot retarget another system.
parse_boot_fstab() {
    esp_source= esp_type= esp_options= esp_point=/boot boot_bind=
    [ -r "$1" ] || return 0
    while read -r source point type flags rest || [ -n "$source" ]; do
        case $source in ''|'#'*) continue ;; esac
        case $point in /boot|/efi) ;; *) continue ;; esac
        if [ "$point" = /boot ] && [ "$type" = none ]; then
            [ "$flags" = bind ] || return 1
            [ -z "$boot_bind" ] || return 1
            case $source in /efi/reliefos/instances/????????-????-????-????-????????????) ;; *) return 1 ;; esac
            instance_uuid=${source##*/}
            case $instance_uuid in *[!0-9a-f-]*) return 1 ;; esac
            [ -z "${2:-}" ] || [ "$instance_uuid" = "$2" ] || return 1
            boot_bind=$source
            continue
        fi
        case $type in vfat|fat32) ;; *) return 1 ;; esac
        [ -z "$esp_source" ] || return 1
        esp_source=$source; esp_type=$type; esp_options=$flags; esp_point=$point
    done < "$1"
    if [ "$esp_point" = /efi ]; then
        [ -n "$boot_bind" ] && [ -n "$esp_source" ] || return 1
    else
        [ -z "$boot_bind" ] || return 1
    fi
    return 0
}
