#!/bin/bash
# Add remaining apps to Homarr board sections

DB_PATH="/volume2/metadata/docker/homarr/appdata/db/db.sqlite"
BOARD_ID="edpkzkkcfz1b8hkwzmevijoc"
LAYOUT_ID="q0a6laa1w1x482hin8cwz597"

ATLANTIS_ID="ku6606knoby4v7wpitg7iup9"
CALYPSO_ID="ulbtudx0jm40cg48yqegce92"
HOMELAB_ID="dy2bps9d4c70n9eqhxcfb6hh"
NUC_ID="dnkfdqkvryetukyag6q6k7ae"
EXTERNAL_ID="9lyej8u8anej7rfstwoa3oc8"
NETWORK_ID="3ma2sicgq2axcwn7uw2gva9v"

echo "=== Adding remaining apps ==="

# Get missing apps
sqlite3 "$DB_PATH" "SELECT a.id, a.name, a.href FROM app a WHERE a.id NOT IN (SELECT json_extract(options, '\$.json.appId') FROM item WHERE kind='app') ORDER BY a.name;" | while IFS='|' read -r app_id name href; do
  [ -z "$app_id" ] && continue

  # Determine section
  if echo "$href" | grep -q "atlantis.vish.local\|vishinator"; then
    SECTION="$ATLANTIS_ID"
    SNAME="Atlantis"
  elif echo "$href" | grep -q "calypso.vish.local\|git.vish.gg"; then
    SECTION="$CALYPSO_ID"
    SNAME="Calypso"
  elif echo "$href" | grep -q "homelab.vish.local"; then
    SECTION="$HOMELAB_ID"
    SNAME="Homelab"
  elif echo "$href" | grep -q "concordnuc.vish.local"; then
    SECTION="$NUC_ID"
    SNAME="NUC"
  elif echo "$href" | grep -q "192.168.8.1\|192.168.29.1\|goodcloud"; then
    SECTION="$NETWORK_ID"
    SNAME="Network"
  else
    SECTION="$EXTERNAL_ID"
    SNAME="External"
  fi

  # Generate item ID
  ITEM_ID=$(cat /dev/urandom | tr -dc 'a-z0-9' | head -c24)

  # Insert item
  sqlite3 "$DB_PATH" "INSERT INTO item (id, board_id, kind, options, advanced_options) VALUES ('$ITEM_ID', '$BOARD_ID', 'app', '{\"json\":{\"appId\":\"$app_id\"}}', '{\"json\":{\"title\":null,\"REDACTED_APP_PASSWORD\":[],\"borderColor\":\"\"}}');"

  # Insert item_layout with position 0,0 (will stack, but that's ok)
  sqlite3 "$DB_PATH" "INSERT INTO item_layout (item_id, section_id, layout_id, x_offset, y_offset, width, height) VALUES ('$ITEM_ID', '$SECTION', '$LAYOUT_ID', 0, 0, 1, 1);"

  echo "  $name -> $SNAME"
done

echo ""
echo "=== Final counts ==="
sqlite3 "$DB_PATH" "SELECT s.name, COUNT(il.item_id) FROM section s LEFT JOIN item_layout il ON s.id = il.section_id WHERE s.name != '' GROUP BY s.id ORDER BY s.name;"

echo ""
echo "=== Restarting Homarr ==="
/var/packages/REDACTED_APP_PASSWORD/target/usr/bin/docker restart homarr
echo "Done!"
