name: XBP helper

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: self-hosted

    steps:
      - name: Check out the repository
        uses: actions/checkout@v4

      - name: Read xbp.json values
        id: parse_json
        shell: bash
        run: |
          set -e

          PROJECT_NAME=$(jq -r '.project_name' .xbp/xbp.json)
          PORT=$(jq -r '.port' .xbp/xbp.json)
          BUILD_DIR=$(jq -r '.build_dir' .xbp/xbp.json)
          CRATE_NAME=$(jq -r '.crate_name' .xbp/xbp.json)

          echo "PROJECT_NAME=$PROJECT_NAME" >> $GITHUB_ENV
          echo "PORT=$PORT" >> $GITHUB_ENV
          echo "BUILD_DIR=$BUILD_DIR" >> $GITHUB_ENV
          echo "CRATE_NAME=$CRATE_NAME" >> $GITHUB_ENV

      - name: Build application
        shell: bash
        run: |
          set -e
          cargo build --release

      - name: Verify build artifact exists
        shell: bash
        run: |
          set -e
          if [ ! -f "$BUILD_DIR/target/release/$CRATE_NAME" ]; then
            echo "Expected binary not found: $BUILD_DIR/target/release/$CRATE_NAME"
            exit 1
          fi

      - name: Run redeploy.sh
        shell: bash
        run: |
          set -e
          chmod +x .xbp/redeploy.sh
          .xbp/redeploy.sh \
            --app-name "$PROJECT_NAME" \
            --port "$PORT" \
            --app-dir "$BUILD_DIR" \
            --crate-name "$CRATE_NAME"
