#!/usr/bin/env bash

# Exit immediately if a command exits with a non-zero status
set -e

# Determine if stdout is a terminal...
if test -t 1; then
    # Determine if colors are supported...
    ncolors=$(tput colors)

    if test -n "$ncolors" && test "$ncolors" -ge 8; then
        BOLD="$(tput bold)"
        YELLOW="$(tput setaf 3)"
        GREEN="$(tput setaf 2)"
        RED="$(tput setaf 1)"
        NC="$(tput sgr0)"
    fi
fi

# Function to handle errors
handle_error() {
    echo "${RED}${BOLD}ERROR: $1${NC}" >&2
    echo "${RED}Sync process failed.${NC}" >&2
    exit 1
}

# Trap errors and call handle_error
trap 'handle_error "Command failed at line $LINENO"' ERR

echo "${BOLD}Running update on Admin container...${NC}" >&2

echo "${YELLOW}Installing composer dependencies...${NC}" >&2
composer install --no-interaction || handle_error "Composer install failed"

echo "${YELLOW}Running main database migrations...${NC}" >&2
php artisan migrate --force || handle_error "Database migration failed"

echo "${YELLOW}Running tenant migrations...${NC}" >&2
php artisan tenants:migrate || handle_error "Tenant migration failed"

echo "${YELLOW}Running tenant seeders...${NC}" >&2
php artisan tenants:seed || handle_error "Tenant seeding failed"

echo "${GREEN}${BOLD}Update finished successfully!${NC}" >&2
