build-deploy:
  stage: build-deploy
  tags:
    - $TARGET
    - $RUNTIME
  rules:
    - if: $EXECUTE_FUNCTIONAL_TEST_PIPELINE == "true"
      when: never
    - when: always
  before_script:
    - echo "🖥️ Installing dependencies"
    - if ! command -v jq &> /dev/null; then apt update && apt install -y jq; else echo "jq is already installed."; fi
    - echo "⚙️ Setting up environment variables"
    # Set error.log path and exit functions scripts
    - export WORKSPACE_PATH=`pwd`
    - export LOG_PATH=`pwd`
    - export FUNCTIONS_PATH=`pwd`/src
  script:
    - echo "🚀 Start pipeline V1.2"
    # Create a root folder to run target script. Important to respect path of all files
    - mkdir target_src
    # Clone target source into target_src
    - ./src/init.sh target_src
    # Remove virtuallab sources and environment variables
    - ./src/clean.sh
    - rm ./src/clean.sh

    # Move to target_src
    - cd target_src
    # Run target scripts
    - if [ ! -s "$LOG_PATH/error.log" ]; then bash ./AI_Support/support.sh; else echo "⏩ support.sh was not executed due to previous errors."; fi
    - if [ ! -s "$LOG_PATH/error.log" ]; then bash ./AI_Build/build.sh; else echo "⏩ build.sh was not executed due to previous errors."; fi
    - if [ ! -s "$LOG_PATH/error.log" ]; then bash ./AI_Deploy/deploy.sh; else echo "⏩ deploy.sh was not executed due to previous errors."; fi
    - if [ ! -s "$LOG_PATH/error.log" ]; then bash ./AI_Manager/manager.sh; else echo "⏩ manager.sh was not executed due to previous errors."; fi

    # Add target_id key to the report file
    - if [ ! -s "$LOG_PATH/error.log" ]; then bash ../src/report_finalizer.sh; else echo "⏩ report_finalizer.sh was skipped."; fi

    # Print any errors
    - |
      echo "Print error.log :"
      cat $LOG_PATH/error.log
    # Print any user log
    - |
      echo "Print user.log :"
      cat $LOG_PATH/user.log


  inherit:
    variables:
      - MODEL_FILENAME
      - DATASET_FILENAME
      - NB_INFERENCE
      - TARGET
      - RUNTIME
      - EXECUTE_FUNCTIONAL_TEST_PIPELINE
      - VIRTUALLAB_PIPELINE_NAME
      - VERSION_TAG
      - BENCHMARK_TYPE

  variables:
      SCRIPT_ERROR: "false" # Automatically set to true by exit_functions.sh if any script fails 
      FUNCTIONS_PATH: "../src/"
  
  environment: $TARGET
  resource_group: $TARGET
  artifacts:
    when: always
    paths:
      - ./target_src/AI_Manager/out
      - ./error.log
      - ./user.log