#!/bin/bash

# Leer credenciales del .env de Laravel
ENV_FILE="/home/forge/taxes.com.ar/.env"
DB_USER=$(grep "^DB_USERNAME=" "$ENV_FILE" | cut -d '=' -f2)
DB_PASS=$(grep "^DB_PASSWORD=" "$ENV_FILE" | cut -d '=' -f2)

# Verificar si el parámetro tdbabuelas_host_id ha sido pasado
if [ -z "$1" ]; then
  echo "Error: Debes proporcionar el tdbabuelas_host_id como parámetro."
  exit 1
fi

# Asignar el parámetro a una variable
TDBABUELAS_HOST_ID=$1

# Variables originales
SV_ARRAY=('localhost')
U_ARRAY=("$DB_USER")
C_ARRAY=("$DB_PASS")
BD_ARRAY=('dbtaxes')

# VARIABLES DEL SCRIPT
index=0
count="${#SV_ARRAY[*]}"

# Crear el directorio de respaldo para la fecha actual
#if [ ! -d $ARCH_RESP ];
#then echo -n "Creando directorio de respaldo DIR_RESP/$ARCH_RESP "
#     mkdir $DIR_RESP/$ARCH_RESP ] && continue
#     echo "done."
#fi

OLDIFS=$IFS
IFS=$'\n'

# Construir la consulta MySQL según el valor de tdbabuelas_host_id
if [ "$TDBABUELAS_HOST_ID" -eq 0 ]; then
  QUERY="SELECT CONCAT('--db=', p.document, ' ', '--schema=', abu_host.host, ',', abu_host.port)
  FROM tdbabuelas abu
  JOIN persons p ON abu.person_id = p.id
  JOIN tdbabuelas_host abu_host ON abu.tdbabuelas_host_id = abu_host.id
  WHERE abu.deleted_at IS NULL;"
else
  QUERY="SELECT CONCAT('--db=', p.document, ' ', '--schema=', abu_host.host, ',', abu_host.port)
  FROM tdbabuelas abu
  JOIN persons p ON abu.person_id = p.id
  JOIN tdbabuelas_host abu_host ON abu.tdbabuelas_host_id = abu_host.id
  WHERE abu.deleted_at IS NULL AND abu.tdbabuelas_host_id = $TDBABUELAS_HOST_ID;"
fi

basedatos=$(mysql -u "$DB_USER" -h "127.0.0.1" -p"$DB_PASS" -se "$QUERY" -D "dbtaxes")

#while [ $index -lt $count ];
#do
# contraseña de mysql
# export USER=${U_ARRAY[$index]-i}
# export MYSQL_PWD=${C_ARRAY[$index]-i}

# echo 'Servidor: '${SV_ARRAY[$index]-i}'---usuario: '$MYUSER'---clave: '$MYPASSWORD
# echo 'conectando a-->'${SV_ARRAY[$index]-i}'<....'

# Realizar Backup de las DB'S
# echo "las bases de datos madres: ${basedatos}";

current_time=$(date +"%Y-%m-%d %H:%M:%S")

contador=0

for linea in $basedatos; do

  ((contador++))

  if [ $contador -eq 1 ]; then
    continue
  fi

  base=$(echo $linea | cut -c6-18)
  param=$(echo $linea | cut -c29-)

  php artisan2.php migrate "--db=$base" "--schema=$param"

done

end_current_time=$(date +"%Y-%m-%d %H:%M:%S")

echo "El proceso inicio: $current_time"
echo "Termino el proceso: $end_current_time"

# unset USER
# unset MYSQL_PWD

# i=$((i+1))
# let "index = $index + 1"

# done
IFS=$OLDIFS
