#!/bin/bash
export PATH=/4PROJECTS/bin:$PATH

# --------------------------------------------------
# Validate parameter
# --------------------------------------------------
if [ -z "$1" ]; then
  echo "Missing Parameters <UUID>"
  exit 1
fi

UUID=$1

# --------------------------------------------------
# Load environment helpers
# --------------------------------------------------
source /4server/sbin/helpers

if ! get_contract_info "$UUID"; then
    echo "Error: Failed to load contract info for $UUID" >&2
    exit 1
fi

# --------------------------------------------------
# Verify container exists
# --------------------------------------------------
if ! doas docker ps -a --format "{{.Names}}" | grep -q "^${UUID}$"; then
    echo "Error: Container $UUID does not exist" >&2
    exit 1
fi

echo "Updating all Odoo modules for database: $UUID"
echo "Using DB host: $POSTGRES_HOST"

# --------------------------------------------------
# Run Odoo update inside container
# --------------------------------------------------
if ! doas docker exec -u odoo "$UUID" odoo \
    -u all \
    -d "$UUID" \
    --stop-after-init \
    --db_host="$POSTGRES_HOST" \
    --db_port="$POSTGRES_PORT" \
    --db_user="$POSTGRES_ADMIN_USER" \
    --db_password="$POSTGRES_ADMIN_PASSWORD"
then
    echo "Error: Odoo module update failed for $UUID" >&2
    exit 1
fi

echo "Module update completed successfully for $UUID"

# --------------------------------------------------
# Restart container
# --------------------------------------------------
echo "Starting container $UUID"
/4server/sbin/startContainer "$UUID"

echo "Done."
exit 0
