image: python:3.12 # Primary docker image to use (you can override this for each job)

stages:
  - install # Define the stages
  - test
  - build
  - release
  - containerize

variables: # Those are global variables that will be inherited by all jobs
  PROJECT_NAME: "cicdiaries" 
  VENV_PATH: .venv 
  IMAGE_TAG: "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" 
  #RUNNER_GENERATE_ARTIFACTS_METADATA: true
  IMAGE_URI: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA


install_deps:
  stage: install
  script:
    - pip install virtualenv
    - virtualenv $VENV_PATH
    - echo "Implement me!" # TODO: install the appm dependencies

code-audit:
  stage: test
  script:
   - echo "Implement me!" # TODO: run code auditing




test:
  stage: test
  needs: [install_deps] # This means that this job must be executed after the app has been installed
  script:
   - echo "Implement me!" # TODO: run tests for the app


lint:
  stage: test
  needs: [install_deps]
  script:
   - echo "Implement me!" # TODO: lint the code

build_binary: # This is a complete step that builds a binary out of the cicdiaries app.
  stage: build
  script: 
    - pip install pyinstaller
    - pip install -r requirements.txt
    - |
      pyinstaller --onefile \
      --add-data "app/website/templates:website/templates" \
      --add-data "app/website/static:website/static" \
      app/wsgi.py
    - tar -czf cicdiaries-binary.tar.gz dist/
  artifacts: # This is a keyword used to tell the pipeline to generate a new artifact
    paths:
      - cicdiaries-binary.tar.gz
    expire_in: 1 week

create_release:
  stage: release
  image: registry.gitlab.com/gitlab-org/release-cli:latest
  dependencies:
    - build_binary
  script:
    - echo "Creating release..."
  # TODO: Create a new release only when a git tag is pushed! see: https://docs.gitlab.com/user/project/releases/release_cicd_examples/#create-a-release-when-a-git-tag-is-created
  # you should also link the artifact that has been generated in the previous job

build_push_image:
  stage: containerize
  image: docker:latest # Here we set a new image to run the job
  before_script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin

  script:
   - echo "Implement me!" # TODO: build and push the image to the registry


sign_image:
  stage: containerize
  image: docker:latest
  variables:
    COSIGN_YES: "true"
    COSIGN_REGISTRY_REFERRERS_MODE: "legacy"
    COSIGN_EXPERIMENTAL: 1

  before_script:
    - apk add --update cosign jq

    - echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin

  script:
    - DIGEST=$(docker inspect --format='{{index .RepoDigests 0}}' "$IMAGE_URI")
    - echo "Implement me!" # TODO: use cosign to sign the image.