#!/bin/bash

DB_NAME="dosis2"  
DB_USER="dsuper" 

# Retrieve all table names in the database
TABLES=$(psql -U "$DB_USER" -d "$DB_NAME" -t -c \
    "SELECT table_schema || '.' || table_name AS tbl FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema');")

# Loop through each table and reindex it with pg_repack
echo "Starting reindexing of all tables in database '$DB_NAME'..."

for TABLE in $TABLES; do
    echo "Reindexing table: $TABLE"
    pg_repack -U "$DB_USER" -d "$DB_NAME" -x -t "$TABLE"

    # Check if the pg_repack command was successful for the table
    if [ $? -ne 0 ]; then
        echo "Reindexing of table $TABLE encountered an error. Skipping to next table."
    else
        echo "Reindexing of table $TABLE completed successfully."
    fi
done

echo "Reindexing of all tables completed."