#!/bin/bash
set -o errexit

# shellcheck source=../env/db.env
source env/db.env
# shellcheck source=../env/magento.env
source env/magento.env

DOMAIN=${1:-magento.test}
ES_HOST=elasticsearch
ES_PORT=9200

bin/download

bin/stop

docker-compose -f docker-compose.yml -f docker-compose.dev.yml up -d
[ $? != 0 ] && echo "Failed to start Docker services" && exit

bin/clinotty chmod u+x bin/magento

echo "Waiting for connection to Elasticsearch..."
bin/clinotty timeout 100 bash -c "
    until curl --silent --output /dev/null http://$ES_HOST:$ES_PORT/_cat/health?h=st; do
        printf '.'
        sleep 2
    done"
[ $? != 0 ] && echo "Failed to connect to Elasticsearch" && exit

sleep 2

bin/clinotty bin/magento setup:install \
  --db-host="$MYSQL_HOST" \
  --db-name="$MYSQL_DATABASE" \
  --db-user="$MYSQL_USER" \
  --db-password="$MYSQL_PASSWORD" \
  --base-url=https://"$DOMAIN"/ \
  --base-url-secure=https://"$DOMAIN"/ \
  --backend-frontname="$MAGENTO_ADMIN_FRONTNAME" \
  --admin-firstname="$MAGENTO_ADMIN_FIRST_NAME" \
  --admin-lastname="$MAGENTO_ADMIN_LAST_NAME" \
  --admin-email="$MAGENTO_ADMIN_EMAIL" \
  --admin-user="$MAGENTO_ADMIN_USER" \
  --admin-password="$MAGENTO_ADMIN_PASSWORD" \
  --language="$MAGENTO_LOCALE" \
  --currency="$MAGENTO_CURRENCY" \
  --timezone="$MAGENTO_TIMEZONE" \
  --search-engine=elasticsearch7 \
  --elasticsearch-host=$ES_HOST \
  --elasticsearch-port=$ES_PORT \
  --use-rewrites=1

echo "Disable Magento 2FAuth module..."
bin/magento module:disable Magento_TwoFactorAuth

echo "Installing Force Login Composer module..."
bin/rootnotty chmod +x bin/magento /var/www/html/BitExpert/ForceCustomerLogin/validate_m2_package.php
bin/rootnotty chown -R app.app /dist
bin/clinotty composer config minimum-stability dev
bin/clinotty composer config "repositories.bitexpert/magento2-force-customer-login" '{"type": "path", "url": "/var/www/html/BitExpert/ForceCustomerLogin/", "options": {"symlink": true}}'
bin/clinotty composer require bitexpert/magento2-force-customer-login:*

echo "Enabling Force Login module..."
bin/clinotty bin/magento module:enable BitExpert_ForceCustomerLogin
bin/clinotty bin/magento setup:upgrade

echo "Forcing deploy of static content to speed up initial requests..."
bin/clinotty bin/magento setup:static-content:deploy -f

echo "Re-indexing with Elasticsearch..."
bin/clinotty bin/magento indexer:reindex

echo "Setting basic URL and generating SSL certificate..."
bin/setup-domain "${DOMAIN}"

echo "Clearing the cache to apply updates..."
bin/clinotty bin/magento cache:flush

echo "Turning on developer mode.."
bin/clinotty bin/magento deploy:mode:set developer

echo "Docker development environment setup complete."
echo "You may now access your Magento instance at https://${DOMAIN}/"
