---
name: Deploy

on:
  push:
    tags:
      - '*'
  workflow_dispatch:

permissions:
  contents: write

jobs:
  test:
    uses: ./.github/workflows/test.yml

  build:
    name: Build and Release
    runs-on: ${{ matrix.os }}
    needs: test

    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-musl
          - os: macos-latest
            target: x86_64-apple-darwin
          - os: windows-latest
            target: x86_64-pc-windows-msvc

    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Extract release version from tag
        if: startsWith(github.ref, 'refs/tags/')
        run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV

      - name: Set up Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install Linux dependencies
        if: matrix.os == 'ubuntu-latest'
        run: sudo apt -y install musl-dev musl-tools

      - name: Build project
        run: cargo build --release --locked --target ${{ matrix.target }}

      - name: Archive build output
        shell: bash
        run: |
          binary_name="backup"
          dirname="$binary_name-${{ env.VERSION }}-${{ matrix.target }}"
          mkdir "$dirname"

          # Move binary to the directory
          if [ "${{ matrix.os }}" == "windows-latest" ]; then
            mv "target/${{ matrix.target }}/release/$binary_name.exe" "$dirname/"
          else
            mv "target/${{ matrix.target }}/release/$binary_name" "$dirname/"
          fi

          # Compress the directory
          if [ "${{ matrix.os }}" == "windows-latest" ]; then
            7z a "$dirname.zip" "$dirname"
            echo "ASSET=$dirname.zip" >> $GITHUB_ENV
          else
            tar -czf "$dirname.tar.gz" "$dirname"
            echo "ASSET=$dirname.tar.gz" >> $GITHUB_ENV
          fi

      - name: Release to GitHub
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v3
        with:
          files: ${{ env.ASSET }}

  publish:
    name: Publish to Crates.io
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Set up Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Publish to Crates.io
        env:
          CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }}
        run: cargo publish --token $CRATES_TOKEN
