name: LinUtil Release

on:
  workflow_dispatch:

permissions:
  contents: write
  packages: write

env:
  CARGO_TERM_COLOR: always

jobs:
  linutil_build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Install musl-tools
        run: sudo apt-get update && sudo apt-get install musl-tools
        
      - name: Cache Cargo registry
        uses: actions/cache@v4
        with:
          path: ~/.cargo/registry
          key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-cargo-registry-

      - name: Cache Cargo index
        uses: actions/cache@v4
        with:
          path: ~/.cargo/git
          key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-cargo-index-

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: x86_64-unknown-linux-musl

      - name: Install cross-rs for cross-compilation
        run: cargo install cross

      - name: Build x86_64 binary
        run: cargo build --target-dir=build --release --verbose --target=x86_64-unknown-linux-musl --all-features

      - name: Build aarch64 binary
        run: cross build --target-dir=build --release --verbose --target=aarch64-unknown-linux-musl --all-features

      - name: Move binaries to build directory
        run: |
          mv build/x86_64-unknown-linux-musl/release/linutil build/linutil
          mv build/aarch64-unknown-linux-musl/release/linutil build/linutil-aarch64

      - uses: stefanzweifel/git-auto-commit-action@v5
        with:
          commit_message: Commit Linutil
          file_pattern: "build/linutil build/linutil-aarch64"
          add_options: '--force'
        if: success()

      - name: Extract Version
        id: extract_version
        run: |
          version=$(date +"%Y.%m.%d")
          echo "version=$version" >> $GITHUB_ENV
        shell: bash

      - name: Build linutil binary
        run: cargo build --release
        
      - name: Create and Upload Release
        id: create_release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ env.version }}
          name: Pre-Release ${{ env.version }}
          body: |
            Latest linutil binary release
          append_body: true
          generate_release_notes: true
          files: |
            ./target/release/linutil
          prerelease: true
        env:
          version: ${{ env.version }}
          DOCKER_ACCESS_TOKEN: ${{ secrets.DOCKER_ACCESS_TOKEN }}
