stages:
  - deploy_stage
  - failed_stage
  - pages_stage

image: alpine:latest # Use the latest version of Alpine Linux docker image

deploy_job:
  stage: deploy_stage

  before_script:
    # Install dependencies
    - 'which ssh-agent || ( apk update && apk add openssh-client git grep)'

    # Run ssh-agent
    - eval $(ssh-agent -s)

    # Import private key with ed25519 workaround
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null

    # Create the SSH directory and give it the right permissions
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh

    # Add gitlab.com as ssh known host
    - ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts

    # Set commit author
    - git config --global user.name "curben-bot"
    - git config --global user.email "curben-bot@users.noreply.gitlab.com"

  script:
    # SSH to gitlab.com
    - ssh git@gitlab.com

    # Shallow cloning for faster cloning
    - git clone --depth 3 git@gitlab.com:curben/urlhaus-filter.git build
    - cd build/

    # Run scripts
    - sh script.sh

    # Commit the changes
    - sh utils/commit.sh

    # Push the commit
    - git push

  after_script:
    # Generate successful status badge
    - mkdir -p /builds/curben/urlhaus-filter/public/
    - wget https://img.shields.io/badge/pipeline-passed-success.svg -O /builds/curben/urlhaus-filter/public/status.svg

  artifacts:
    paths:
      - public/status.svg

  only:
    # Allow CI to be triggered by schedule
    - schedules

    # Allow CI to be triggered manually
    - web

failed_job:
  stage: failed_stage

  script:
    # Generate failed status badge
    - mkdir -p /builds/curben/urlhaus-filter/public/
    - wget https://img.shields.io/badge/pipeline-failed-critical.svg -O /builds/curben/urlhaus-filter/public/status.svg

  artifacts:
    paths:
      - public/status.svg

  # Run this job only when deploy_job failed
  when: on_failure

  only:
    - schedules
    - web

pages:
  stage: pages_stage

  script:
    - echo "Uploading status.svg to Pages..."

  artifacts:
    paths:
      - public

  when: always

  only:
    - schedules
    - web
