version: 0.2
env:
  exported-variables:
    - AWS_REGION
    - AWS_ACCOUNT_ID
    - CODEBUILD_BUILD_ID
    - CODEBUILD_BUILD_NUMBER
    - CODEBUILD_PUBLIC_BUILD_URL
    - CODEBUILD_SOURCE_VERSION
    - BRANCH_NAME
    - COMMIT_ID
    - S3_MAGENTO_ENV_PATH
  secrets-manager:
    DB_ROOT_USER: $MAGENTO_CONFIG_SECRET_ARN:DB_ROOT_USER
    DB_ROOT_PASSWORD: $MAGENTO_CONFIG_SECRET_ARN:DB_ROOT_PASSWORD
    DB_PORT: $MAGENTO_CONFIG_SECRET_ARN:DB_PORT
    MAGENTO_ENV_PHP_LOCATION: $MAGENTO_CONFIG_SECRET_ARN:MAGENTO_ENV_PHP_LOCATION
    MAGENTO_CONFIG_PHP_LOCATION: $MAGENTO_CONFIG_SECRET_ARN:MAGENTO_CONFIG_PHP_LOCATION
phases:
  pre_build:
    commands:
      - echo Entered the pre_build phase...
      - echo "Checking if the new user exists"
      # Write SQL to check if the user exists and create if necessary
      - echo "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '${DB_USER}');" > check_user.sql
      - user_exists=$(mysql -u${DB_ROOT_USER} -p${DB_ROOT_PASSWORD} -h${DB_HOST} --batch --skip-column-names < check_user.sql)

      # If user doesn't exist, create it
      - if [ "$user_exists" -eq 0 ]; then
        echo "Creating new user ${DB_USER}";
        echo "CREATE USER IF NOT EXISTS '${DB_USER}'@'%' IDENTIFIED BY '${DB_PASSWORD}';" > create_user.sql;
        cat create_user.sql;
        mysql -u${DB_ROOT_USER} -p${DB_ROOT_PASSWORD} -h${DB_HOST} < create_user.sql;
        else
        echo "User ${DB_USER} already exists";
        fi

      # Write SQL to check if the database exists and create if necessary
      - echo "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${DB_NAME}';" > check_db.sql
      - db_exists=$(mysql -u${DB_ROOT_USER} -p${DB_ROOT_PASSWORD} -h${DB_HOST} --batch --skip-column-names < check_db.sql)

      # If the database doesn't exist, create it and grant privileges
      - if [ -z "$db_exists" ]; then
        echo "Creating new database ${DB_NAME} and assigning user ${DB_USER}";
        echo "CREATE DATABASE IF NOT EXISTS ${DB_NAME}; GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%'; FLUSH PRIVILEGES;" > create_db.sql;
        mysql -u${DB_ROOT_USER} -p${DB_ROOT_PASSWORD} -h${DB_HOST} < create_db.sql;
        else
        echo "Database ${DB_NAME} already exists";
        fi

      # Check if the customer_entity table exists
      - TABLE_QUERY="SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '${DB_NAME}' AND table_name = 'customer_entity';"
      - TABLE_EXISTS=$(mysql -u "$DB_ROOT_USER" -p"$DB_ROOT_PASSWORD" -h "$DB_HOST" -e "$TABLE_QUERY" --batch --skip-column-names)
      - if [ "$TABLE_EXISTS" -eq 0 ]; then
        echo "Table ${DB_NAME}.customer_entity does not exist.";
        export TABLE_CUSTOMER_ENTITY_EXISTS="false";
        else
        echo "Table ${DB_NAME}.customer_entity exists.";
        export TABLE_CUSTOMER_ENTITY_EXISTS="true";
        TABLE_CUSTOMER_ENTITY_COUNT_QUERY="SELECT COUNT(entity_id) AS qty FROM ${DB_NAME}.customer_entity;";
        TABLE_CUSTOMER_ENTITY_COUNT_RESULT=$(mysql -u${DB_ROOT_USER} -p${DB_ROOT_PASSWORD} -h${DB_HOST} -e "$TABLE_CUSTOMER_ENTITY_COUNT_QUERY" --batch --skip-column-names);
        fi

      # Check if this store is a new one or a existing one
      - if [ "$TABLE_CUSTOMER_ENTITY_EXISTS" = "true" ] && [ "$TABLE_CUSTOMER_ENTITY_COUNT_RESULT" -gt 0 ]; then
        echo "Table ${DB_NAME}.customer_entity has [${TABLE_CUSTOMER_ENTITY_COUNT_RESULT}] rows. This is a existing store";
        export IS_NEW_STORE="false";
        else
        echo "Table ${DB_NAME}.customer_entity does not exists or does not have data. This is a new store";
        export IS_NEW_STORE="true";
        fi

      #Check if the env.php exists
      - ENV_PHP_CHECK=$(aws s3 ls s3://$MAGENTO_ENV_PHP_LOCATION || true)
      - if [ -z "$ENV_PHP_CHECK" ]; then
        echo "env.php file ${MAGENTO_ENV_PHP_LOCATION} does not exist in S3.";
        export MAGENTO_INSTALLED="false";
        else
        echo "env.php file ${MAGENTO_ENV_PHP_LOCATION} exists in S3.";
        export MAGENTO_INSTALLED="true";
        fi

  build:
    commands:
      - echo Entering the build phase...
      - echo Build started on `date`
      - php -v
      - php -m
      - printenv
      - composer install
      - chmod +x bin/magento
      - ls -ll
      - if [ "$MAGENTO_INSTALLED" = "true" ]; then
        echo "*********************************************************";
        echo "Magento is already installed, downloading config files";
        echo "*********************************************************";
        echo "Downloading env.php and config.php from S3";
        aws s3 cp s3://$MAGENTO_ENV_PHP_LOCATION app/etc/env.php;
        aws s3 cp s3://$MAGENTO_CONFIG_PHP_LOCATION app/etc/config.php;
        else
        echo "*********************************************************";
        echo "Magento is not installed, proceeding with installation...";
        echo "*********************************************************";
        bin/magento setup:install --base-url=$MAGENTO_BASE_URL --backend-frontname=admin --admin-firstname=$MAGENTO_ADMIN_FIRSTNAME --admin-lastname=$MAGENTO_ADMIN_LASTNAME --admin-email=$MAGENTO_ADMIN_EMAIL --admin-user=$MAGENTO_ADMIN_USER --admin-password=$MAGENTO_ADMIN_PASSWORD --language=$MAGENTO_LANGUAGE --currency=$MAGENTO_CURRENCY --timezone=$MAGENTO_TIMEZONE --use-rewrites=1 --db-host=$DB_HOST --db-name=$DB_NAME --db-user=$DB_USER --db-password=$DB_PASSWORD --search-engine=opensearch --opensearch-host=$OPENSEARCH_HOST --opensearch-port=$OPENSEARCH_PORT --opensearch-enable-auth=0 --opensearch-index-prefix=$OPENSEARCH_INDEX_PREFIX --opensearch-timeout=15 --consumers-wait-for-messages=1 --enable-debug-logging=true --enable-syslog-logging=true --session-save=redis --session-save-redis-host=$REDIS_HOST --session-save-redis-port=6379 --session-save-redis-db=$REDIS_SESSION_SAVE_DB --cache-backend=redis --cache-backend-redis-server=$REDIS_HOST --cache-backend-redis-db=$REDIS_CACHE_BACKEND_DB --page-cache-redis-server=$REDIS_HOST --page-cache-redis-db=$REDIS_PAGE_CACHE_DB;
        bin/magento module:disable Magento_AdminAdobeImsTwoFactorAuth Magento_TwoFactorAuth;
        echo "Uploading config.php and env.php to S3";
        aws s3 cp app/etc/config.php s3://$MAGENTO_CONFIG_PHP_LOCATION;
        aws s3 cp app/etc/env.php s3://$MAGENTO_ENV_PHP_LOCATION;
        echo "*********************************************************";
        echo "Magento installation completed";
        echo "*********************************************************";
        fi
      - echo Build completed on `date`
artifacts:
  files:
    - '**/*'

  name: builds/$CODEBUILD_BUILD_NUMBER
