#!/bin/bash

coll="$1"

r='rasql --user rasadmin --passwd rasadmin'
colors=(White Silver Grey Orange Brown Maroon Green Olive Purple DarkBlue \
LightBlue Bisque BurlyWood CadetBlue Chocolate Coral Crimson DarkCyan DarkGray \
DarkMagenta DarkSlateGreen DarkTurquoise Green HotPink Indigo Lavender MidnightBlue \
Peru RosyBrown SaddleBrown Sienna Teal Yellow)

get_bounds() {
  lo1=${sdom[0]}
  hi1=${sdom[1]}
  lo2=${sdom[2]}
  hi2=${sdom[3]}
  w=$(($hi1 - $lo1 + 1))
  h=$(($hi2 - $lo2 + 1))
}
get_color() {
  colorno=$((${#colors[@]} - 1))
  idx=$(shuf -i 0-$colorno -n 1)
  color=${colors[$idx]}
}
decompose_sdom() {
  sdom=($($r -q "select sdom(c) from $coll as c" --out string | grep Result | \
          sed 's/.*\[//' | sed 's/[,:\]]*/ /g' | tr -d ']'))
  get_bounds
}

decompose_sdom

echo "<svg width='$w' height='$h'>"

for s in $($r -q "select dbinfo(c, \"printtiles=1\") from $coll as c" --out string | strings | grep $'\t\t"\[' | tr -d $'\t' | sed 's/,$//g'); do
  sdom=($(echo "$s" | tr -d '"' | tr -d ']' | tr -d '[' | sed 's/[:,]/ /g'))
  get_bounds
  get_color
  echo "<rect x=\"$lo1\" y=\"$lo2\" width=\"$w\" height=\"$h\" fill=\"$color\" stroke=\"black\"></rect>"
done

echo "</svg>"
