#!/bin/bash
#

# This script uses the instanceId value of the EC2 instance to configure
# the default passwords for Magento, Zammad, and databases.


function checkStatusCode(){
        echo `/usr/bin/curl -o /dev/null -I -s -w "%{http_code}" $1 --insecure`
}


NGINX_CONF_FILE="/home/docker/magento-backend/config/tls/nginx.conf"
NGINX_CONF_FILE_BASE="${NGINX_CONF_FILE}_base"
NGINX_STATUS_FILE="/home/docker/magento-backend/config/tls/status.html"
ZAMMAD_GATEWAY_ENV_FILE="/home/docker/zammad-gateway/.env"
ZAMMAD_GATEWAY_ENV_FILE_BASE="${ZAMMAD_GATEWAY_ENV_FILE}_base"
ZAMMAD_GATEWAY_DOCKER_COMPOSE_FILE="/home/docker/zammad-gateway/docker-compose.yml"

instancePublicIP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)
instanceId=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r '.instanceId')
last6chars=${instanceId:13:6}

DEBUG_FILE="/home/ubuntu/userDataDebug.txt"

echo "Instance info:" >> $DEBUG_FILE
echo "Instance ID: $instanceId" >> $DEBUG_FILE
echo "Public IP: $instancePublicIP" >> $DEBUG_FILE

# Modify status file to not ready
echo "Modify the status file to not ready"
sudo echo "B2BStore is starting... Please wait." > $NGINX_STATUS_FILE

# Check MariaDB status
echo "Checking MariaDB status...." >> $DEBUG_FILE
mysqladmin ping --protocol tcp -u root -pOrienteed.B2BStore
statusCode=$?
while [ $statusCode -ne 0 ]
do
        echo "statusCode=$statusCode" >> $DEBUG_FILE
        sleep 5
        mysqladmin ping --protocol tcp -u root -pOrienteed.B2BStore >> $DEBUG_FILE
        statusCode=$?
done

## MariaDB passwords
sleep 10

echo "Updating MariaDB passwords:"  >> $DEBUG_FILE
statusCode=-1
while [ $statusCode -ne 0 ]
do
        echo sudo -u docker docker exec magento-backend_db_1 mysql -u root -pOrienteed.B2BStore -e "ALTER USER 'root'@'%' IDENTIFIED BY 'B2BStore.$instanceId'" >> $DEBUG_FILE
        sudo -u docker docker exec magento-backend_db_1 mysql -u root -pOrienteed.B2BStore -e "ALTER USER 'root'@'%' IDENTIFIED BY 'B2BStore.$instanceId'" >> $DEBUG_FILE
        statusCode=$?
        sleep 2
done

statusCode=-1
while [ $statusCode -ne 0 ]
do
        echo sudo -u docker docker exec magento-backend_db_1 mysql -u root -pOrienteed.B2BStore -e "ALTER USER 'root'@'localhost' IDENTIFIED BY 'B2BStore.$instanceId'"  >> $DEBUG_FILE
        sudo -u docker docker exec magento-backend_db_1 mysql -u root -pOrienteed.B2BStore -e "ALTER USER 'root'@'localhost' IDENTIFIED BY 'B2BStore.$instanceId'" >> $DEBUG_FILE
        statusCode=$?
        sleep 2
done

statusCode=-1
while [ $statusCode -ne 0 ]
do
        echo sudo -u docker docker exec magento-backend_db_1 mysql -u root -pB2BStore.$instanceId -e "ALTER USER 'B2BStore_user'@'%' IDENTIFIED BY 'B2BStore_DB_$last6chars'"   >> $DEBUG_FILE
        sudo -u docker docker exec magento-backend_db_1 mysql -u root -pB2BStore.$instanceId -e "ALTER USER 'B2BStore_user'@'%' IDENTIFIED BY 'B2BStore_DB_$last6chars'" >> $DEBUG_FILE
        statusCode=$?
        sleep 2
done

statusCode=-1
while [ $statusCode -ne 0 ]
do
        echo sudo -u docker docker exec magento-backend_db_1 mysql -u root -pB2BStore.$instanceId -e "FLUSH PRIVILEGES;" >> $DEBUG_FILE
        sudo -u docker docker exec magento-backend_db_1 mysql -u root -pB2BStore.$instanceId -e "FLUSH PRIVILEGES;" >> $DEBUG_FILE
        statusCode=$?
        sleep 2
done

# Stop TLS container to avoid connections
echo "Stop TLS container to avoid connections" >> $DEBUG_FILE
sudo -u docker docker stop magento-backend_tls_1 >> $DEBUG_FILE

# Check Magento status
echo "Checking Magento status" >> $DEBUG_FILE
statusCode=$(checkStatusCode http://localhost/status)
while [ $statusCode -ne 200 ]
do
        echo "StatusCode=$statusCode" >> $DEBUG_FILE
        sleep 5
        statusCode=$(checkStatusCode http://localhost/status)
        echo "StatusCode=$statusCode" >> $DEBUG_FILE
done

## Magento passwords

# Change Magento password for database
echo "Change Magento password for database:" >> $DEBUG_FILE
echo sudo -u docker docker exec magento-backend_fpm_1 php bin/magento setup:config:set --db-password="B2BStore_DB_$last6chars" --no-interaction  >> $DEBUG_FILE
sudo -u docker docker exec magento-backend_fpm_1 php bin/magento setup:config:set --db-password="B2BStore_DB_$last6chars" --no-interaction >> $DEBUG_FILE

# Change Magento admin URI in nginx config
echo "Change Magento admin URI in nginx config" >> $DEBUG_FILE
sed 's/:::ADMIN-URI:::/'"admin_$last6chars"'/g' $NGINX_CONF_FILE_BASE > $NGINX_CONF_FILE

# Restart nginx container to apply new config
#sudo -u docker docker restart magento-backend_tls_1

# Change Magento admin URI in Magento config
echo "Change Magento admin URI in Magento config" >> $DEBUG_FILE
echo sudo -u docker docker exec magento-backend_fpm_1 php bin/magento setup:config:set --backend-frontname="admin_$last6chars" --no-interaction >> $DEBUG_FILE
sudo -u docker docker exec magento-backend_fpm_1 php bin/magento setup:config:set --backend-frontname="admin_$last6chars" --no-interaction

# Change Magento admin password
echo "Change Magento admin password" >> $DEBUG_FILE
echo sudo -u docker docker exec magento-backend_fpm_1 php bin/magento admin:user:create --admin-user=admin --admin-password=B2BStore.$last6chars --admin-email=admin@admin.com --admin-firstname=admin --admin-lastname=admin -n >> $DEBUG_FILE
sudo -u docker docker exec magento-backend_fpm_1 php bin/magento admin:user:create --admin-user=admin --admin-password=B2BStore.$last6chars --admin-email=admin@admin.com --admin-firstname=admin --admin-lastname=admin -n >> $DEBUG_FILE

# Change Magento customer password
echo "Change Magento customer password" >> $DEBUG_FILE
echo sudo -u docker docker exec magento-backend_db_1 mysql -u B2BStore_user -pB2BStore_DB_$last6chars B2BStore -e "UPDATE customer_entity SET password_hash = CONCAT(SHA2('xxxxxxxxB2BStore.$last6chars', 256), ':xxxxxxxx:1') WHERE email like 'p.mestieri@b2bstore.io';" >> $DEBUG_FILE
sudo -u docker docker exec magento-backend_db_1 mysql -u B2BStore_user -pB2BStore_DB_$last6chars B2BStore -e "UPDATE customer_entity SET password_hash = CONCAT(SHA2('xxxxxxxxB2BStore.$last6chars', 256), ':xxxxxxxx:1') WHERE email like 'p.mestieri@b2bstore.io';" >> $DEBUG_FILE

# Reindex
echo "Do a reindex in Magento" >> $DEBUG_FILE
sudo -u docker docker exec magento-backend_fpm_1 php bin/magento indexer:reindex

## Zammad
# Wait for it to start

echo "Waiting for Zammad to start" >> $DEBUG_FILE
statusCode=$(checkStatusCode http://localhost:8080)
while [ $statusCode -ne 200 ]
do
        sleep 5
        statusCode=$(checkStatusCode http://localhost:8080)
done

# Setup admin password
echo "Setup Zammad admin password" >> $DEBUG_FILE
sudo -u docker docker exec zammad_zammad-railsserver_1 rails runner 'User.find_by(email: "admin@admin.com").update!(password: "B2BStore.'$last6chars'")'

# Create Zammad token
echo "Create Zammad token" >> $DEBUG_FILE
sudo -u docker docker exec zammad_zammad-railsserver_1 rails runner 'Token.create(user_id: 3, persistent: true, action: "api", label: "B2B", preferences: {"permission"=>["admin.group", "admin.object", "admin.organization", "ticket.agent"]}, created_at: Time.now, updated_at: Time.now)'
token=$(sudo -u docker docker exec zammad_zammad-railsserver_1 rails runner 'p Token.last.name' | grep -Po '[^"]*(?="$)')


# Apply token in zammad-gateway
echo "Apply token in zammad-gateway" >> $DEBUG_FILE
sudo sed 's/:::ZAMMAD_API_KEY:::/'"$token"'/g' $ZAMMAD_GATEWAY_ENV_FILE_BASE > $ZAMMAD_GATEWAY_ENV_FILE

# Restart zammad-gateway container
echo "Restart zammad-gateway container" >> $DEBUG_FILE
sudo -u docker docker-compose -f $ZAMMAD_GATEWAY_DOCKER_COMPOSE_FILE up -d --build


# Start TLS container
echo "Start TLS container" >> $DEBUG_FILE
sudo -u docker docker start magento-backend_tls_1

# Stop frontend container
echo "Stop frontend container" >> $DEBUG_FILE
sudo -u docker docker stop b2bstore

# Clear and flush Magento cache and restart varnish
echo "Clear and flush Magento cache (this might require multiple attempts on the first start)" >> $DEBUG_FILE
sudo -u docker docker restart magento-backend_varnish_1 >> $DEBUG_FILE
sudo -u docker docker restart magento-backend_fpm_1 >> $DEBUG_FILE
sudo rm -r /home/docker/magento-backend/mymagento-magento-sync/var/cache/*

# Test backend URI status
statusCode=$(checkStatusCode "https://$instancePublicIP/admin_$last6chars")
while [ $statusCode -ne 200 ]
do
        echo "Retrying to clear and flush Magento cache" >> $DEBUG_FILE
        sleep 2
        sudo -u docker docker exec magento-backend_fpm_1 php /app/bin/magento cache:clean >> $DEBUG_FILE
        sudo -u docker docker exec magento-backend_fpm_1 php /app/bin/magento cache:flush >> $DEBUG_FILE
        statusCode=$(checkStatusCode "https://$instancePublicIP/admin_$last6chars") >> $DEBUG_FILE
        echo $statusCode >> $DEBUG_FILE
done


# Stop TLS container to avoid connections
echo "Stop TLS container to avoid connections" >> $DEBUG_FILE
sudo -u docker docker stop magento-backend_tls_1 


# Start frontend container
echo "Start frontend container" >> $DEBUG_FILE
sudo -u docker docker start b2bstore
sleep 10

# Recompile frontend
echo "Recompile frontend (this might take a few minutes)" >> $DEBUG_FILE
sudo -u docker docker exec b2bstore yarn venia run build:prod

# Restart frontend container
echo "Restart frontend container" >> $DEBUG_FILE
sudo -u docker docker restart b2bstore

# Modify status file to ready
echo "Modify the status file to ready"
sudo echo "B2BStore is now ready for connections." > $NGINX_STATUS_FILE

# Start TLS container
echo "Start TLS container" >> $DEBUG_FILE
sudo -u docker docker start magento-backend_tls_1

echo "FINISHED" >> $DEBUG_FILE