stages:
  - check
  - build
  - package
  - deploy

variables:
  DOCKER_REGISTRY: "docker.io"
  IMAGE_BACKEND: "docker.io/benarbause/doodleback-with-quarkus:latest"
  IMAGE_FRONTEND: "docker.io/vuminh224/doodle-frontend:latest"
  APP_REPO: "https://github.com/barais/doodlestudent.git"
  SUBMODULE_PATH: "doodlestudent"

check_app_update:
  stage: check
  image: debian:latest
  tags:
    - docker
  script:
    - apt-get update
    - apt-get install -y git
    # Récupère le dernier commit distant
    - LATEST_REMOTE=$(git ls-remote $APP_REPO HEAD | awk '{print $1}')
    # Récupère le commit actuel du submodule
    - CURRENT_SUBMODULE=$(git rev-parse HEAD:$SUBMODULE_PATH || echo "none")
    # Compare
    - |
      if [ "$LATEST_REMOTE" != "$CURRENT_SUBMODULE" ]; then
        echo "NEW_COMMIT=true" >> variables.env
      else
        echo "NEW_COMMIT=false" >> variables.env
      fi
  artifacts:
    paths:
      - variables.env

# Build Frontend (Angular)
build_frontend:
  stage: build
  image: node:current-alpine3.23
  tags:
    - docker
  dependencies:
    - check_app_update
  script:
    - apk add --no-cache git
    - git submodule update --init --recursive
    - source variables.env || true
    - if [ "$NEW_COMMIT" != "true" ]; then
      echo "No new commit, skipping build";
      exit 0;
      fi
    - ls -la doodlestudent/front #test
    - cd doodlestudent/front
    - npm ci
    - npm run build --prod
  artifacts:
    paths:
      - doodlestudent/front/dist/


# Build & Push Docker frontend
build_docker_frontend:
  stage: package
  tags:
    - shell
  dependencies:
    - check_app_update
    - build_frontend
  script:
    - source variables.env || true
    - if [ "$NEW_COMMIT" != "true" ]; then
      echo "No new commit, skipping build";
      exit 0;
      fi
    - echo "$DOCKERHUB_TOKEN" | docker login -u "$DOCKERHUB_USER" --password-stdin
    - docker build -t "$IMAGE_FRONTEND" doodlestudent/front
    - docker push "$IMAGE_FRONTEND"
    - docker logout
# Deploy to Production
deploy_production:
  stage: deploy
  image: alpine:latest
  dependencies:
    - build_docker_frontend
    - check_app_update
  tags:
    - docker
  before_script:
    - apk add --no-cache openssh-client docker-cli
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa
    - ssh-keyscan -H "$DEPLOY_SERVER" >> ~/.ssh/known_hosts 2>/dev/null || true
  script:
    - source variables.env || true
    - if [ "$NEW_COMMIT" != "true" ]; then
      echo "No new commit, skipping build";
      exit 0;
      fi
    - |
      ssh "$DEPLOY_USER@$DEPLOY_SERVER" << 'EOF'
      cd /app
      docker compose pull
      docker compose up -d
      EOF
  environment:
    name: production
    url: http://148.60.11.130
  when: manual