image: wordpress:php8.3-fpm
stages:
  - deploy_staging
  - deploy_prod
before_script:
  - echo "Starting before_script section"

  # Install Composer
  - curl -sS https://getcomposer.org/installer | php
  - mv composer.phar /usr/local/bin/composer

  # Install deps needed
  - apt-get update && apt-get install -y curl unzip zip git rsync sshpass openssh-client libxml2-dev gnupg

   # Install Node.js 20 (overwrite old version)
  - curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
  - apt-get install -y nodejs
  - node -v
  - npm -v

  # Enable SimpleXML
  - docker-php-ext-install simplexml
deploy_staging:
  stage: deploy_staging
  script:
    - echo "Starting build script with Vite.js"
    # - cd app/public/
    - rm composer.lock
    - composer install

    - cd web/app/themes/interlude-theme
    - rm -rf node_modules package-lock.json
    - rm composer.lock
    - composer install
    - npm install
    - npm run build
    - cd ../../../../
    - echo "Preparing for staging deployment"
    # - rm .env
    - mv .env-staging .env
    # Debugging section
    - echo "Adding SSH host to known_hosts for staging"
    - mkdir -p ~/.ssh
    - ssh-keyscan -p "$SSH_PORT_STAGING" "$SSH_HOST_STAGING" >> ~/.ssh/known_hosts
    - echo "SSH_PORT_STAGING \"$SSH_PORT_STAGING\""
    - echo "SSH_HOST_STAGING \"$SSH_HOST_STAGING\""
    - echo "SSH_USER_STAGING \"$SSH_USER_STAGING\""
    - echo "SSH_PATH_STAGING \"$SSH_PATH_STAGING\""
    # Display and debug rsync command
    - echo "Deploying to staging server via rsync"
    - rm -rf .git
    - echo "rsync command sshpass -p \"$SSH_PASSWORD_STAGING\" rsync -avz --delete --exclude='web/app/uploads/*' --exclude='node_modules/*' -e \"ssh -p $SSH_PORT_STAGING\" ./ \"$SSH_USER_STAGING@$SSH_HOST_STAGING:$SSH_PATH_STAGING\""
    - sshpass -p "$SSH_PASSWORD_STAGING" rsync -avz --delete --exclude='web/app/uploads/*' --exclude='node_modules/*' -e "ssh -p $SSH_PORT_STAGING" ./ "$SSH_USER_STAGING@$SSH_HOST_STAGING:$SSH_PATH_STAGING"
  environment:
    name: staging
  only:
    - staging
  when: manual
deploy_prod:
  stage: deploy_prod
  script:
    - echo "Starting build script with Vite.js"
    - composer install
    - cd web/app/themes/interlude-theme
    - composer install
    - rm -rf node_modules package-lock.json
    - npm install
    - npm run build
    - cd ../../../../

    # Préparation .env
    - echo "Preparing for production deployment"
    - rm -f .env
    - mv .env-prod .env

    # Ajout SSH host
    - mkdir -p ~/.ssh
    - ssh-keyscan -p $SSH_PORT $SSH_HOST >> ~/.ssh/known_hosts

    # Déploiement
    - echo "Deploying to PROD via rsync"

    - sshpass -p "$SSH_PASSWORD" rsync -avz --delete --exclude='web/app/uploads/*' --exclude='node_modules/*' -e "ssh -p $SSH_PORT" ./ $SSH_USER@$SSH_HOST:$SSH_PATH || [[ $? -eq 23 ]]

  environment:
    name: production
  only:
    - main
  when: manual
