13 KiB
GitHub Copilot Instructions for Shell Repository
This document provides context and guidance for GitHub Copilot when working with this shell script and dotfiles repository.
Repository Overview
This repository contains:
- Shell scripts for system administration tasks
- Dotfiles for system configuration
- Setup scripts for automated environment configuration
- Docker-based testing framework for validating setup across environments
Repository Structure
- Root directory: Contains various utility shell scripts
- docs/: Documentation for individual scripts and components
- dotfiles/: System configuration files that get symlinked to the user's home directory
- powershell/: PowerShell scripts for Windows environments
- setup/: Setup scripts and package lists for automated environment configuration
- .github/: GitHub-related configuration files
Key Files Overview
Shell Scripts
- bootstrap.sh: Entry point script for automated setup
- test-setup.sh: Testing script for validating environment setup
- run-docker-tests.sh: Runner for Docker-based testing
- update.sh: System update scripts
- plex.sh: Plex Media Server management
Configuration Files
- setup/packages.list: List of packages to install during setup
- dotfiles/my-aliases.zsh: Custom ZSH aliases
- dotfiles/tailscale-acl.json: Tailscale ACL configuration
Documentation
- README.md: Main repository documentation
- docs/docker-bootstrap-testing-framework.md: Detailed documentation for the Docker-based bootstrap validation framework
- dotfiles/README.md: Documentation for dotfiles setup and usage
Plex Scripts
- plex.sh: Main Plex Media Server management script
- backup-plex.sh: Automated backup system for Plex databases and configurations
- monitor-plex-backup.sh: Monitoring and reporting for backup operations
- restore-plex.sh: Database and configuration restoration utilities
- validate-plex-backups.sh: Backup integrity verification system
- test-plex-backup.sh: Testing framework for backup operations
- integration-test-plex.sh: End-to-end integration testing for Plex services
- plex-recent-additions.sh: Recent media additions reporting
Style Guidelines
When suggesting code or modifications:
-
Shell Scripts:
- Use
#!/bin/bashfor most scripts - Include proper error handling with
set -ewhere appropriate - For test scripts, avoid
set -eto allow testing all components - Add descriptive comments for script sections
- Use colors for terminal output when appropriate (GREEN, RED, YELLOW, etc.)
- Use capitalized variable names (e.g.,
USER_HOME=/home/user)
- Use
-
Docker Files:
- Follow Docker best practices for layer optimization
- Use specific tags for base images rather than 'latest'
- Include proper LABEL directives for metadata
-
Documentation:
- Use proper Markdown formatting
- Include code examples using appropriate syntax highlighting
- Document script parameters and usage
Testing Framework
When modifying the testing framework:
- Make sure to test across both Ubuntu and Debian environments
- Ensure tests continue even when individual components fail
- Track and summarize all errors at the end of tests
- Maintain proper error reporting and logging
Docker Testing Enhancements
The Docker-based testing framework includes these key features:
-
Continuous Testing: Tests continue running even when individual package installations fail
- Achieved by removing
set -efrom test scripts - Uses a counter to track errors rather than exiting immediately
- Achieved by removing
-
Package Testing:
- Dynamically reads packages from
setup/packages.list - Tests each package individually
- Maintains an array of missing packages for final reporting
- Dynamically reads packages from
-
Summary Reporting:
- Provides a comprehensive summary of all failed tests
- Suggests commands to fix missing packages
- Saves detailed logs to a timestamped file
-
Cross-Platform Testing:
- Tests both Ubuntu and Debian environments
- Handles platform-specific package names (e.g.,
batvsbatcat)
Key Concepts
- Shell Environment Setup: Focuses on ZSH with Oh My Zsh and plugins
- Docker Testing: Validates environment setup in isolated containers
- Dotfiles Management: Uses symbolic links to user's home directory
- Package Installation: Uses apt/nala on Debian-based systems
Main Use Cases
- Setting up a new development environment: Using bootstrap.sh
- Managing media services: Using plex.sh and related scripts
- System maintenance: Using update.sh and backup scripts
- Testing configuration changes: Using the Docker testing framework
Code Organization Principles
- Modularity: Keep scripts focused on one task
- Documentation: Document all scripts and configurations
- Testing: Ensure all changes are testable
- Cross-platform: Support both Ubuntu and Debian where possible
Security Practices
When suggesting security-related code:
-
Permissions:
- Avoid running scripts as root unless necessary
- Use
sudofor specific commands rather than entire scripts - Set appropriate file permissions (e.g.,
chmod 600for sensitive files)
-
Secret Management:
- Never include hardcoded credentials in scripts
- Use environment variables or external secret management
- Add sensitive files to .gitignore
-
Input Validation:
- Validate and sanitize all user inputs
- Use quotes around variables to prevent word splitting and globbing
- Implement proper error handling for invalid inputs
-
Network Security:
- Verify URLs before downloading (
curl/wget) - Use HTTPS instead of HTTP when possible
- Validate checksums for downloaded packages
- Verify URLs before downloading (
Contribution Guidelines
For contributors and Copilot suggestions:
-
Script Modifications:
- Test all changes using the Docker testing framework
- Update documentation when adding new functionality
- Maintain backward compatibility when possible
-
New Scripts:
- Follow the established naming conventions
- Include a header with description, usage, and author
- Add appropriate documentation to the docs/ directory
- Add any new dependencies to setup/packages.list
-
Review Process:
- Run tests before submitting changes
- Document what was changed and why
- Consider both Ubuntu, Debian, and Fedora compatibility
Automatic Code Validation and Critical Error Checking
When generating or modifying shell scripts, GitHub Copilot must automatically validate code and check for critical errors before suggesting changes.
Mandatory Validation Checks
-
Syntax Validation:
- Always verify proper
if/fi,for/done,while/donematching - Check for balanced brackets:
[,],[[,]] - Ensure proper function definition syntax:
function_name() { ... } - Validate case statement structure:
case/esacmatching - Check for missing quotes around variables in conditions
- Always verify proper
-
Control Flow Validation:
- Verify
elsestatements have correspondingifstatements - Check that nested conditionals are properly indented and closed
- Ensure
breakandcontinueare only used within loops - Validate that functions return appropriate exit codes
- Verify
-
Variable and Quote Validation:
- Always quote variables to prevent word splitting:
"$VARIABLE" - Check for undefined variables being used
- Validate array syntax and indexing
- Ensure proper escaping in strings containing special characters
- Always quote variables to prevent word splitting:
Critical Logic Error Patterns to Check
Based on analysis of plex scripts, watch for these common issues:
-
Service Management Logic:
# CORRECT: Check service status before operations if sudo systemctl is-active --quiet plexmediaserver; then sudo systemctl stop plexmediaserver fi # INCORRECT: Assuming service state without checking sudo systemctl stop plexmediaserver # May fail if already stopped -
File Operation Safety:
# CORRECT: Check file existence and permissions if [[ -f "$BACKUP_FILE" && -r "$BACKUP_FILE" ]]; then # Process file else echo "Error: Backup file not found or not readable" exit 1 fi # INCORRECT: Operating on files without validation tar -xzf "$BACKUP_FILE" # May fail silently -
Directory Operations:
# CORRECT: Verify directory creation and permissions if ! mkdir -p "$BACKUP_DIR"; then echo "Error: Failed to create backup directory" exit 1 fi # Set proper permissions chmod 755 "$BACKUP_DIR" # INCORRECT: Assuming directory operations succeed mkdir -p "$BACKUP_DIR" cd "$BACKUP_DIR" # May fail if mkdir failed -
Database Operations:
# CORRECT: Validate database integrity before and after operations if ! sqlite3 "$DB_FILE" "PRAGMA integrity_check;" | grep -q "ok"; then echo "Error: Database integrity check failed" exit 1 fi # INCORRECT: Operating on database without validation sqlite3 "$DB_FILE" ".backup backup.db" # May corrupt if DB is damaged -
Parallel Processing Safety:
# CORRECT: Proper parallel job management with wait for file in "${files[@]}"; do process_file "$file" & ((++job_count)) # Limit concurrent jobs if (( job_count >= MAX_JOBS )); then wait job_count=0 fi done wait # Wait for remaining jobs # INCORRECT: Uncontrolled parallel execution for file in "${files[@]}"; do process_file "$file" & # May overwhelm system done
Error Handling Patterns
-
Function Error Handling:
# CORRECT: Proper function with error handling backup_database() { local db_file="$1" local backup_file="$2" if [[ -z "$db_file" || -z "$backup_file" ]]; then echo "Error: Missing required parameters" return 1 fi if [[ ! -f "$db_file" ]]; then echo "Error: Database file not found: $db_file" return 1 fi if ! sqlite3 "$db_file" ".backup $backup_file"; then echo "Error: Database backup failed" return 1 fi return 0 } -
Cleanup on Error:
# CORRECT: Cleanup trap for error handling cleanup() { if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then rm -rf "$TEMP_DIR" fi if [[ "$SERVICE_STOPPED" == "true" ]]; then sudo systemctl start plexmediaserver fi } trap cleanup EXIT ERR
Validation Checklist for Code Generation
Before suggesting any shell script code, verify:
- All
ifstatements have matchingfi - All
for/whileloops have matchingdone - All
casestatements have matchingesac - Functions are properly defined with
()and{} - Variables are quoted in conditions and expansions
- File operations check for existence and permissions
- Service operations verify current state before changes
- Database operations include integrity checks
- Parallel operations are properly managed with job limits
- Error handling includes cleanup and restoration
- Exit codes are properly set and checked
- Temporary files and directories are cleaned up
Testing Integration
When modifying scripts:
- Syntax Check: Always run
bash -n script.shvalidation - Logic Testing: Test with various input conditions
- Error Scenarios: Test failure modes and recovery
- Integration Testing: Verify interaction with system services
- Permission Testing: Test with different user privileges
Common Anti-Patterns to Avoid
-
Unmatched Control Structures:
# WRONG: Missing fi if [[ condition ]]; then do_something # Missing fi here -
Unsafe Variable Expansion:
# WRONG: Unquoted variables if [ $VAR = "value" ]; then # Will break if VAR contains spaces # CORRECT: if [[ "$VAR" = "value" ]]; then -
Ignoring Command Failures:
# WRONG: Not checking critical command results sudo systemctl stop plexmediaserver # Continue without knowing if stop succeeded # CORRECT: if ! sudo systemctl stop plexmediaserver; then echo "Error: Failed to stop Plex service" exit 1 fi -
Race Conditions in Service Management:
# WRONG: Race condition sudo systemctl stop plexmediaserver sudo systemctl start plexmediaserver # May start before stop completes # CORRECT: sudo systemctl stop plexmediaserver sleep 2 # Allow time for clean shutdown sudo systemctl start plexmediaserver