stages:
  - build
  - release

variables:
  # Use official NixOS container
  NIX_IMAGE: "nixos/nix:latest"
  # Binary path relative to project root
  BINARY_PATH: "build/compose/binaries/main/app/Theorycrafter/bin/Theorycrafter"
  
build:
  stage: build
  image: $NIX_IMAGE
  
  # Only run on new tags for main branch
  only:
    - tags
  
  before_script:
    - echo "Setting up Nix environment..."
    - nix --version
    - nix-channel --update
    
  script:
    - echo "Building Java project with Gradle via Nix shell..."
    # Enter nix-shell and run the build
    - nix-shell --run "./gradlew package"
    
    # Verify the binary exists
    - ls -la $BINARY_PATH
    - file $BINARY_PATH
    
    # Create the tarball with the tag name
    - mkdir -p release
    - tar -czf "release/Theorycrafter-${CI_COMMIT_TAG}-x86_64-linux.tar.gz" -C "$(dirname $BINARY_PATH)" "$(basename $BINARY_PATH)"
    - ls -l release
    
    # Verify the tarball was created
    - ls -la release/
    
  artifacts:
    paths:
      - release/Theorycrafter-${CI_COMMIT_TAG}-x86_64-linux.tar.gz
    expire_in: 1 week
    
  cache:
    key: gradle-cache-$CI_COMMIT_REF_SLUG
    paths:
      - .gradle/caches/
      - .gradle/wrapper/

release:
  stage: release
  image: registry.gitlab.com/gitlab-org/release-cli:latest
  
  # Only run on new tags for main branch
  only:
    - tags
    
  # Depend on build job completion
  dependencies:
    - build
    
  before_script:
    - apk add --no-cache curl jq
    
  script:
    - echo "Creating GitLab release for tag ${CI_COMMIT_TAG}..."
    
    # Create release using GitLab Release CLI
    - |
      release-cli create \
        --name "Theorycrafter ${CI_COMMIT_TAG}" \
        --tag-name "${CI_COMMIT_TAG}" \
        --description "Release ${CI_COMMIT_TAG}" \
        --assets-link "{\"name\":\"Theorycrafter-${CI_COMMIT_TAG}-x86_64-linux.tar.gz\",\"url\":\"${CI_PROJECT_URL}/-/jobs/${CI_JOB_ID}/artifacts/file/release/Theorycrafter-${CI_COMMIT_TAG}-x86_64-linux.tar.gz\"}"

