#!/bin/bash
# panel-db list                         — TSV: database, size MB, tables, users with access
# panel-db create <database> <user>     — create database + user (password read from stdin), grant all on it
# panel-db dump <database>              — gzip-compressed SQL backup on stdout
# panel-db map                          — TSV: database, sites whose config files mention it (cached 6 h)
# panel-db on <server> <command…>       — the same on a connected server
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
if [ "${1:-}" = on ]; then
  srv="${2:-}"; ip=$(node_ip "$srv") || die "unknown server: $srv"; shift 2
  [[ "${1:-}" =~ ^(list|create|dump|map)$ ]] || die "not allowed there: ${1:-}"
  exec ssh "${NODE_SSH_OPTS[@]}" "root@$ip" "/opt/panel/bin/panel-db $(printf '%q ' "$@")"
fi
case "${1:-}" in
  dump)   # gzip-compressed SQL backup on stdout
    db="${2:-}"; [[ "$db" =~ ^[A-Za-z0-9_]{1,64}$ ]] || die "bad database name"
    [[ ! "$db" =~ ^(mysql|sys|performance_schema|information_schema)$ ]] || die "system databases are not downloadable"
    mysql -N -B -e "select 1 from information_schema.schemata where schema_name='$db'" | grep -q 1 || die "no such database: $db"
    nice -n 10 mysqldump --single-transaction --quick --routines --triggers --no-tablespaces "$db" | nice -n 10 gzip -6
    ;;
  map)    # TSV: database, sites whose config files mention it (cached for 6 h)
    c=/var/lib/panel/db-map.tsv
    if [ ! -s "$c" ] || [ -n "$(find "$c" -mmin +360 2>/dev/null)" ] || [ "${2:-}" = fresh ]; then
      names=$(mktemp); tmp=$(mktemp); trap 'rm -f "$names" "$tmp"' EXIT
      mysql -N -B -e "select schema_name from information_schema.schemata where schema_name not in ('mysql','sys','performance_schema','information_schema')" > "$names"
      if [ -s "$names" ]; then
        for f in "$PANEL_VHOSTS"/*.conf; do
          [ -f "$f" ] || continue; d=$(basename "$f" .conf); r=$(site_docroot "$d"); [ -d "$r" ] || continue
          timeout 20 find "$r" -maxdepth 3 -type f \( -iname '*config*.php' -o -iname 'db*.php' -o -iname '*database*.php' -o -iname 'settings*.php' -o -iname 'conn*.php' -o -name '.env' -o -name '*.ini' \) -size -200k -print0 2>/dev/null \
            | xargs -0 -r grep -hoFw -f "$names" 2>/dev/null | sort -u | sed "s/\$/\t$d/" >> "$tmp" || true
        done
      fi
      sort -u "$tmp" > "$tmp.s"; trap 'rm -f "$names" "$tmp" "$tmp.s"' EXIT
      awk -F'\t' 'NR==FNR{n[$2]++; next} n[$2]<=6{a[$1]=a[$1] (a[$1]?" ":"") $2} END{for(k in a) print k "\t" a[k]}' "$tmp.s" "$tmp.s" | sort > "$c.new" && mv -f "$c.new" "$c"
    fi
    cat "$c" 2>/dev/null || true
    ;;
  list)
    mysql -N -B -e "
      select s.schema_name,
             coalesce(round(sum(t.data_length+t.index_length)/1048576,1),0),
             count(t.table_name),
             coalesce((select group_concat(distinct d.user order by d.user separator ' ') from mysql.db d
                        where s.schema_name like replace(d.db,'\\\\_','\\_')),'')
        from information_schema.schemata s left join information_schema.tables t on t.table_schema=s.schema_name
       where s.schema_name not in ('mysql','sys','performance_schema','information_schema')
       group by s.schema_name order by s.schema_name"
    ;;
  create)
    db="${2:-}"; user="${3:-}"
    [[ "$db" =~ ^[A-Za-z0-9_]{1,64}$ ]] || die "database name: letters, digits, _ only"
    [[ "$user" =~ ^[A-Za-z0-9_]{1,32}$ ]] || die "user name: letters, digits, _ only (max 32)"
    IFS= read -r pass || true
    [ ${#pass} -ge 12 ] || die "password must be at least 12 characters"
    p=${pass//\\/\\\\}; p=${p//\'/\\\'}
    mysql -e "CREATE DATABASE IF NOT EXISTS \`$db\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
              CREATE USER IF NOT EXISTS '$user'@'localhost' IDENTIFIED BY '$p';
              GRANT ALL PRIVILEGES ON \`$db\`.* TO '$user'@'localhost'; FLUSH PRIVILEGES;"
    echo "created database $db with user $user"
    ;;
  *) die "usage: panel-db list | create <db> <user> | dump <db> | map | on <server> …";;
esac
