#!/bin/bash

# pipeInxi (similar to pipeNeofetch)

# call from .config/openbox/menu.xml like
#        <menu id="inxi" label="inxi" execute="pipeInxi" />

# mk rnd tmp
tmp="/tmp/$RANDOM-$$"
trap '[ -n "$tmp" ] && rm -fr "$tmp"' EXIT
mkdir -m 700 "$tmp" || { echo '!! unable to create a tmpdir' >&2; tmp=; exit 1; }

# header
header () {
cat << HEAD
<openbox_pipe_menu>
HEAD
}

# footer
footer () {
cat << FOOT
</openbox_pipe_menu>
FOOT
}

xmlescape () {
    echo "$@" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'"'"'/\&#39;/g; s/^[ \t]*//;s/[ \t]*$//'
}

# checks critical
command -v inxi >/dev/null 2>&1 || { header; echo "<item label=\"Horrible error, I need inxi installed.\" />"; footer ; exit 1; }

# make some tmp files, how about all at once
inxido () {
    
    c="0"
    array=( -S -M -C -G -A -N no-D no-P -s -I ) # ignore option by adding 'no'
    for i in "${array[@]}"
    do

        if ! [[ "$i" =~ ^no.*  ]]; then
        ( (inxi "$i" -c 0 | tr -s ' ' & wait) > "$tmp/$c" ) &
        ((c=c+1))
        fi
        
    done
    wait
    
}
inxido || exit

pretty () {
    
    for file in "$tmp"/*
    do
        cut -d ' ' -f1 "$file" > "$tmp/tmp"
        cut -d ' ' -f2- "$file" >> "$tmp/tmp"
        mv "$tmp/tmp" "$file" || exit
        
    done
}   
pretty || exit

# count files for '<separator/>' purposes
count="$(ls -1q "$tmp" | wc -l)"

# main
header
# items loop over files and over lines in those files
c="0"
for file in "$tmp"/*
do
    ((c=c+1))
    while read -r line
    do 

        if (( ${#line} > 2 )); then
            line=$(xmlescape "$line")
            line="${line//_/__}"
            echo "<item label=\"$line\">
                <action name=\"Execute\">
                    <execute>
                        bash -c \"echo '$line' | /usr/bin/xsel --clipboard\"
                    </execute>
                </action>
            </item>"
        fi
        
    done <"$file"

    #echo "<item label=\" \" />"
    (( c < count )) && echo "<separator/>"

done
footer