name: Untar and Commit Files

on:
  push:
    branches:
      - book
    paths:
      - 'today/archive.tar.gz' # 或实际文件名
  # 可选：允许手动触发
  workflow_dispatch:
  
jobs:
  untar_and_commit_job:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    env:
      TAR_FILE_PATH: "today/archive.tar.gz" # 或实际文件名
      DESTINATION_REPO_PATH: "today"
      TEMP_EXTRACT_DIR: "temp_extracted"

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          lfs: true # 添加这个以防万一，如果不用LFS也没关系

      - name: Diagnose file
        run: |
          echo "Looking for file: ${{ env.TAR_FILE_PATH }}"
          if [ -f "${{ env.TAR_FILE_PATH }}" ]; then
            echo "File found. Details:"
            ls -lh "${{ env.TAR_FILE_PATH }}"
            echo "File type reported by 'file' command:"
            file "${{ env.TAR_FILE_PATH }}"
          else
            echo "Error: File ${{ env.TAR_FILE_PATH }} not found!"
            exit 1
          fi

      - name: Untar file to a temporary location
        run: |
          mkdir -p ${{ env.TEMP_EXTRACT_DIR }}
          echo "Untarring ${{ env.TAR_FILE_PATH }} to ${{ env.TEMP_EXTRACT_DIR }}"
          # === Based on your diagnosis, the file is a POSIX tar archive (uncompressed) ===
          # tar -xzf "${{ env.TAR_FILE_PATH }}" -C "${{ env.TEMP_EXTRACT_DIR }}" # Original, incorrect for this scenario
          tar -xf "${{ env.TAR_FILE_PATH }}" -C "${{ env.TEMP_EXTRACT_DIR }}"
          # tar -xjf "${{ env.TAR_FILE_PATH }}" -C "${{ env.TEMP_EXTRACT_DIR }}"
          # tar -xJf "${{ env.TAR_FILE_PATH }}" -C "${{ env.TEMP_EXTRACT_DIR }}"
          echo "Untar complete. Contents of temporary directory:"
          ls -R ${{ env.TEMP_EXTRACT_DIR }}

      # ... 后续步骤 (Move/Sync, Clean up, Commit and push) 保持不变 ...
      - name: Move/Sync untarred files to destination path in repo
        run: |
          echo "Moving/Syncing files from ${{ env.TEMP_EXTRACT_DIR }} to ${{ env.DESTINATION_REPO_PATH }}"
          rsync -av --delete "${{ env.TEMP_EXTRACT_DIR }}/" "${{ env.DESTINATION_REPO_PATH }}/"
          echo "Sync complete. Contents of destination directory:"
          ls -R ${{ env.DESTINATION_REPO_PATH }}

      - name: Clean up temporary directory
        run: rm -rf ${{ env.TEMP_EXTRACT_DIR }}

      - name: Commit and push changes
        uses: stefanzweifel/git-auto-commit-action@v5
        with:
          commit_message: "Docs: Auto-update from ${{ env.TAR_FILE_PATH }}"
          file_pattern: "${{ env.DESTINATION_REPO_PATH }}/**"
          commit_user_name: "GitHub Actions Bot"
          commit_user_email: "actions@github.com"
          commit_author: "GitHub Actions Bot <actions@github.com>"
