#!/bin/bash
BASE_URL=${1:-magento2.test}

bin/stop

# get rid of vertex/module-tax, not required and causes checksum errors on composer install
# https://github.com/markshust/docker-magento/issues/135
sed -e 's/"require-dev": {/"replace": { "vertex\/module-tax": "*" },\ "require-dev": {/' src/composer.json | tee 'src/composer.json' > /dev/null

docker-compose -f docker-compose.yml up -d
sleep 1 #Ensure containers are started...

echo "Copying all files from host to container..."
rm -rf src/vendor #Clear for step below
bin/copytocontainer --all

bin/clinotty chmod u+x bin/magento

echo "Forcing reinstall of composer deps to ensure perms & reqs..."
bin/clinotty composer install

bin/clinotty bin/magento setup:install \
  --db-host=db \
  --db-name=magento \
  --db-user=magento \
  --db-password=magento \
  --base-url=https://$BASE_URL/ \
  --admin-firstname=John \
  --admin-lastname=Smith \
  --admin-email=john.smith@gmail.com \
  --admin-user=john.smith \
  --admin-password=password123 \
  --language=en_US \
  --currency=USD \
  --timezone=America/New_York \
  --use-rewrites=1

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

bin/clinotty bin/magento indexer:reindex

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

echo "Enabling redis for cache..."
bin/clinotty bin/magento setup:config:set --no-interaction --cache-backend=redis --cache-backend-redis-server=redis --cache-backend-redis-db=0

echo "Enabling Redis for session..."
bin/clinotty bin/magento setup:config:set --no-interaction --session-save=redis --session-save-redis-host=redis --session-save-redis-log-level=4 --session-save-redis-db=1

echo "Clearing the cache for good measure..."
bin/clinotty bin/magento cache:flush

echo "Copying files from container to host after install..."
bin/copyfromcontainer app
bin/copyfromcontainer vendor

echo "Restarting containers with host bind mounts for dev..."
bin/restart

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