# Gitea Actions Setup Guide

This guide explains how to set up the CI auto-sort system for Gitea Actions.

## 🚀 Quick Setup

### 1. Enable Gitea Actions
Ensure your Gitea instance has Actions enabled:
- **Admin Panel**: Go to Site Administration → Actions
- **Enable Actions**: Check "Enable Actions for this repository"
- **Runner**: Ensure at least one runner is available

### 2. Create CI Bot Token
1. **Navigate to User Settings**:
   - Click your profile → Settings → Applications
2. **Generate New Token**:
   - Token Name: `CI Auto-Sort Bot`
   - Scopes: Select `repo` (Repository access)
   - Click "Generate Token"
3. **Copy Token**: Save the generated token securely

### 3. Add Repository Secret
1. **Go to Repository Settings**:
   - Navigate to your repository → Settings → Secrets
2. **Add New Secret**:
   - Name: `CI_BOT_TOKEN`
   - Value: Paste the token from step 2
   - Click "Add Secret"

### 4. Add Repository Variables
1. **Go to Repository Settings**:
   - Navigate to your repository → Settings → Variables
2. **Add Worker Email Variable**:
   - Name: `WORKER_EMAIL`
   - Value: Email for git commits (e.g., `ci-bot@your-domain.com`)
   - Click "Add Variable"
3. **Add Worker Username Variable**:
   - Name: `WORKER_USERNAME`
   - Value: Username for git commits (e.g., `CI Auto-Sort Bot`)
   - Click "Add Variable"

### 5. Enable Repository Actions
1. **Repository Settings**: Go to Settings → Actions
2. **Enable Actions**: Check "Enable Actions"
3. **Allow all actions**: Select appropriate action permissions

## 🔧 Detailed Configuration

### Token Permissions
The `CI_BOT_TOKEN` requires these permissions:
- **Repository**: Full access to repository contents
- **Contents**: Read and write access to files
- **Metadata**: Read repository metadata
- **Pull requests**: Read pull request information (for PR triggers)

### Workflow Configuration
The workflow file is located at `.gitea/workflows/auto-sort-files.yml` and includes:

```yaml
name: Auto-Sort Files
on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]
```

### Authentication Method
The workflow uses token-based authentication and dynamically detects the repository URL:
```yaml
- name: Checkout repository
  uses: actions/checkout@v4
  with:
    token: ${{ secrets.CI_BOT_TOKEN }}
```

The push operation automatically detects the repository URL:
```bash
# Get the repository URL dynamically
REPO_URL=$(git config --get remote.origin.url)
# Supports both HTTPS and SSH repository URLs
```

## 🧪 Testing the Setup

### 1. Create Test Files
Create test files with the correct prefixes:
```bash
# Create a test datasheet
echo "Test datasheet content" > DS_test-component_datasheet_2024-08-11.pdf

# Create a test image
echo "Test image content" > IMG_test-diagram_v1.0.0_2024-08-11.png
```

### 2. Commit and Push
```bash
git add .
git commit -m "Test CI auto-sort system"
git push
```

### 3. Verify Workflow Execution
1. **Actions Tab**: Go to your repository → Actions
2. **Check Workflow**: Look for "Auto-Sort Files" workflow
3. **View Logs**: Click on the workflow run to see detailed logs
4. **Verify Results**: Check if files were moved to correct directories

## 📋 Troubleshooting

### Common Issues

#### Workflow Not Running
- **Check Actions Enabled**: Verify Actions are enabled in repository settings
- **Check Runner**: Ensure Gitea has available runners
- **Check Triggers**: Verify push was to main/develop branch

#### Permission Denied
- **Token Scope**: Ensure token has `repo` scope
- **Token Validity**: Check if token hasn't expired
- **Secret Name**: Verify secret is named exactly `CI_BOT_TOKEN`

#### Files Not Moving
- **File Prefix**: Ensure files start with `DS_` or `IMG_`
- **File Extensions**: Check supported extensions (PDF, PNG, JPG, etc.)
- **Already Sorted**: Files already in correct location won't be moved

### Debug Steps
1. **Check Workflow Logs**:
   - Go to Actions tab → Select workflow run → View logs
2. **Verify Token**:
   - Test token permissions with a simple git operation
3. **Manual Test**:
   - Run the bash script locally to test file detection

## 🔒 Security Considerations

### Token Security
- **Scope Limitation**: Use minimal required scopes
- **Regular Rotation**: Rotate tokens periodically
- **Access Control**: Limit who can access repository secrets

### Workflow Security
- **Branch Protection**: Protect main branch from direct pushes
- **Review Process**: Require PR reviews for workflow changes
- **Audit Logs**: Monitor Actions execution logs

## 🎯 Advanced Configuration

### Custom File Types
Add support for additional file types by modifying the workflow:

```bash
# Add CAD files
find . -name "CAD_*.step" -o -name "CAD_*.sldprt" | while read file; do
  if [[ "$file" != ./mechanical/cad/* ]]; then
    filename=$(basename "$file")
    move_file "$file" "mechanical/cad/$filename"
  fi
done
```

### Subdirectory Sorting
Implement intelligent subdirectory sorting:

```bash
# Sort datasheets by component type
case "$filename" in
  DS_STM32*|DS_ESP32*) dest_dir="docs/datasheets/microcontrollers/" ;;
  DS_LM*|DS_AMS*) dest_dir="docs/datasheets/power-management/" ;;
  DS_USB*|DS_JST*) dest_dir="docs/datasheets/connectors/" ;;
  *) dest_dir="docs/datasheets/" ;;
esac
```

### Notification Integration
Add notifications for successful sorts:

```yaml
- name: Notify on Slack
  if: steps.sort_files.outputs.files_moved == 'true'
  uses: 8398a7/action-slack@v3
  with:
    status: success
    text: "Files automatically sorted by CI"
  env:
    SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
```

## 📊 Monitoring and Maintenance

### Regular Checks
- **Weekly**: Review auto-sort commits
- **Monthly**: Check workflow execution statistics
- **Quarterly**: Rotate CI bot token

### Performance Optimization
- **File Size Limits**: Monitor for large files that slow down workflow
- **Execution Time**: Optimize script for large repositories
- **Runner Resources**: Ensure adequate runner capacity

## 🆘 Support

### Getting Help
- **Gitea Documentation**: https://docs.gitea.io/en-us/usage/actions/
- **Repository Issues**: Use the issue tracker for template-specific problems
- **Community**: Gitea community forums and Discord

### Reporting Issues
When reporting issues, include:
- Gitea version
- Workflow logs
- Repository structure
- Error messages
- Steps to reproduce

---

## ✅ Setup Checklist

- [ ] Gitea Actions enabled on instance
- [ ] CI bot token created with `repo` scope
- [ ] `CI_BOT_TOKEN` secret added to repository
- [ ] `WORKER_EMAIL` variable added to repository
- [ ] `WORKER_USERNAME` variable added to repository
- [ ] Repository Actions enabled
- [ ] Test files created and pushed
- [ ] Workflow executed successfully
- [ ] Files moved to correct directories
- [ ] Team members trained on prefix usage

**Once all items are checked, your CI auto-sort system is ready!** 🎉
