#!/bin/bash


export PGPASSWORD=password
export URL=postgresql://user@host:5432/db


export SQL_CHECK="select * from pg_proc p where not exists (  select 1  from pg_catalog.pg_namespace where oid = p.pronamespace );"

# Function to run the SQL script and check the result
run_thread() {
  thread_name=$1

  echo "Starting $thread_name"

  while :; do
  
    echo "[$thread_name] $(date)"
    echo "[$thread_name] Running install script"
    psql -f search_bug.sql $URL

    echo "[$thread_name] Checking result of check_sql"
    result=$(psql -t -c "$SQL_CHECK" $URL | xargs)

    if [[ -n "$result" ]]; then
      echo "[$thread_name] Found problem, stopping thread."
      break
    fi

    echo "[$thread_name] Restarting loop."
    sleep 1 # Optional: Prevent tight looping
    
    # Generate a random delay using $RANDOM and awk
    random_delay=$(awk -v vrand="$RANDOM" 'BEGIN { print (vrand % 900 + 100) / 1000 }')
    echo "[$thread_name] Sleeping for $random_delay seconds."
    sleep "$random_delay"
    
  done
}


# Start threads in the background
run_thread "Thread1"  &
pid1=$!

run_thread "Thread2"  &
pid2=$!

# Wait for both threads to complete
wait $pid1
wait $pid2

echo "Both threads have completed."
