]> git.vanrenterghem.biz Git - elgato-keylight-script.git/blobdiff - keylights.sh
Co-authored-by: JonssonViktor <JonssonViktor@users.noreply.github.com>
[elgato-keylight-script.git] / keylights.sh
index d3b293a308050dbd8bd5cc12d2c4b1abcfe23f6f..1dab5117c592013987618a3dc38ace9061065da6 100755 (executable)
@@ -157,16 +157,15 @@ output() {
     json) print_json "$lights_json" ;;
     simple) print_json "$simple_json" ;;
     flat) print_json "$flat_json" ;;
-    table) print_structured "$simple_json" '@tsv' ;;
-    csv) print_structured "$simple_json" '@csv' ;;
-    pair) print_pairs "$simple_json" ;;
-    html) print_html "$simple_json" ;;
+    table) print_structured '@tsv' ;;
+    csv) print_structured '@csv' ;;
+    pair) print_structured 'pairs' ;;
+    html) print_html ;;
     -?*) die "Unknown output format (-f/--format): $format" ;;
     esac
 }
 
 print_json() {
-    # TODO: Evaluate adding jq filtering as filter argument
 
     # Manage pretty printing
     if [[ $pretty -eq 1 ]]; then
@@ -179,27 +178,43 @@ print_json() {
 }
 
 print_structured() {
-    query="(.[0] | keys_unsorted | map(ascii_upcase)), (.[] | [.[]])|${2-@csv}"
+    pp=${2-$pretty}
+    # Handle csv and table printing
+    query="(.[0] | keys_unsorted | map(ascii_upcase)), (.[] | [.[]])|${1-@csv}"
 
-    # Manage pretty printing
-    if [[ $pretty -eq 1 ]]; then
-        echo "${1-}" | jq --raw-output "$query" | column -t -s$'\t'
-    else
-        echo "${1-}" | jq -r "$query"
+    # Handle printing as key value pairs
+    if [[ ${1} == 'pairs' ]]; then
+        query='.[] | "--------------",(to_entries[] | [.key, "=", .value] | @tsv)'
     fi
-}
-
-print_pairs() {
-    query='.[] | "--------------",(to_entries[] | [.key, "=", .value] | @tsv)'
 
     # Manage pretty printing
-    if [[ $pretty -eq 1 ]]; then
-        echo "${1-}" | jq --raw-output "$query" | column -t -s$'\t'
+    if [[ $pp -eq 1 ]]; then
+        echo "${simple_json}" | jq --raw-output "$query" | column -t -s$'\t' | sed -e 's/"//g'
     else
-        echo "${1-}" | jq "$query"
+        echo "${simple_json}" | jq -r "$query"
     fi
 }
 
+print_html() {
+    data=$(print_structured '@csv' 1)
+
+    html="
+    <table>
+    $(
+        print_header=true
+        while read d; do
+            if $print_header; then
+                echo "<tr><th>${d//,/<\/th><th>}</th></tr>"
+                print_header=false
+                continue
+            fi
+            echo "<tr><td>${d//,/</td><td>}</td></tr>"
+        done <<<"${data}"
+    )
+    </table>"
+    echo "$html"
+}
+
 set_state() {
     new_state=$1
     die "To be implemented"
@@ -287,7 +302,7 @@ dependencies avahi-browse curl notify-send jq
 find_lights
 
 # Fail if we cannot find lights
-[[ ${#lights[@]} -eq 0 ]] && die "No lights found" 2
+[[ ${#lights[@]} -eq 0 ]] && die "No lights found"
 
 produce_json