stages:
  - test
  - deploy

variables:
  DOMAIN_SUFFIX: "preprod.uxpro.com.br"
  DOMAIN_SUFFIX_PROD: "olhodivino.uxpro.com.br"

test:
  stage: test
  tags:
    - preprod-0
  only:
    - merge_requests
  script:
    - echo "Iniciando o Deploy no Servidor de Testes..."
    - /script/criar-projeto.sh "$CI_COMMIT_REF_SLUG.$CI_PROJECT_NAME"

    - export SITE_PATH="/var/www/${CI_COMMIT_REF_SLUG}.$CI_PROJECT_NAME.${DOMAIN_SUFFIX}"
    - echo "$SITE_PATH"
    - export CI_PROJECT_PATH="$(pwd)"
    - echo "$CI_PROJECT_PATH"
    - cd "$SITE_PATH"
    - sudo pwd
    - sudo rm -rf "$SITE_PATH"/*
    - sudo cp -R "$CI_PROJECT_PATH"/* "$SITE_PATH"
    - sudo chown -R www-data:www-data "$SITE_PATH"
    - sudo chmod -R 777 "$SITE_PATH"
    - sudo systemctl restart apache2
    - echo "https://${CI_COMMIT_REF_SLUG}.$CI_PROJECT_NAME.${DOMAIN_SUFFIX}"

deploy:
  stage: deploy
  tags:
    - React-sv0
  only:
    - main
    - master
  when: manual
  script:
    - echo "🚀 Iniciando o Deploy no Servidor Produção..."
    - /script/criar-projeto.sh "$DOMAIN_SUFFIX_PROD"
    - export SITE_PATH="/var/www/${DOMAIN_SUFFIX_PROD}"
    - export CI_PROJECT_PATH="$(pwd)"
    - echo "$CI_PROJECT_PATH"
    - cd "$SITE_PATH"
    - sudo pwd
    #- sudo bash -c 'shopt -s extglob && cd "$SITE_PATH" && sudo rm -rf !("config.json")'
    #- sudo find "$SITE_PATH" -mindepth 1 ! -name 'config.json' -exec rm -rf {} +
    - sudo find "$SITE_PATH" -mindepth 1 ! -name 'db' ! -name 'db' ! -path "$SITE_PATH/db/*" ! -path "$SITE_PATH/db/*" -exec rm -rf {} +

    - sudo cp -Rn "$CI_PROJECT_PATH"/* "$SITE_PATH"
    - sudo chown -R www-data:www-data "$SITE_PATH"
    - sudo chmod -R 777 "$SITE_PATH"
    - sudo systemctl restart apache2
    - echo "https://${DOMAIN_SUFFIX_PROD}"
