# Build and Deployment Guide

This document provides comprehensive procedures for building and deploying MPV.Rocks Installer across all platforms.

## Table of Contents

- [Prerequisites](#prerequisites)
- [Building](#building)
- [Cross-Compilation](#cross-compilation)
- [Testing Builds](#testing-builds)
- [Packaging](#packaging)
- [Release Procedure](#release-procedure)
- [Deployment](#deployment)

---

## Prerequisites

### Development Environment

**Required Tools:**
- Go 1.25 or later
- Make (for build automation)
- Git (optional, for version info)
- Go modules: `go mod` for dependency management

**Recommended IDEs:**
- GoLand (JetBrains)
- VS Code with Go extension
- Neovim with nvim-go
- Vim with vim-go

### Platform-Specific Tools

**Windows:**
- MinGW-w64 (TDM-GCC) for CGO compilation
- PowerShell (for Windows-specific commands)
- Resource hacker (for Windows resources)

**Linux:**
- GCC/Clang (for CGO compilation)
- build-essential packages
- Package managers: apt, dnf, pacman

**macOS:**
- Xcode Command Line Tools
- Xcode (for CGO compilation)
- Resource utilities (if creating .app bundles)

### Go Module Dependencies

```bash
# Install all dependencies
go mod download

# Verify dependencies
go mod verify

# Tidy dependencies
go mod tidy
```

---

## Building

### Build All Platforms

```bash
# Build for current platform
make build

# Build for all platforms
make build-all

# Build specific platform
make build-linux-x86_64
make build-windows-x86_64
make build-macos-arm64
```

### Platform-Specific Builds

#### Windows x86_64

```bash
# Standard build (with v2 baseline for compatibility)
GOOS=windows GOARCH=amd64 GOAMD64=v2 go build \
  -ldflags="-s -w -X main.version=$(git describe --tags --always --dirty)" \
  -o dist/mpv-manager-win-x86_64.exe ./cmd/mpv-manager

# With embedded resources
make build-windows-x86_64
```

**Important:** Always use `GOAMD64=v2` for Windows x86_64 builds to ensure compatibility with older CPUs (Sandy Bridge 2011+).

#### Linux x86_64

```bash
# Standard build
GOOS=linux GOARCH=amd64 go build \
  -ldflags="-s -w -X main.version=$(git describe --tags --always --dirty)" \
  -o dist/mpv-manager-linux-x86_64 ./cmd/mpv-manager

# With static binary
CGO_ENABLED=0 go build -ldflags="-s -w" \
  -tags netgo,osusergo,netgo \
  -o dist/mpv-manager-linux-x86_64-static ./cmd/mpv-manager
```

#### macOS

**Universal Binary (Recommended):**
```bash
# Build both architectures
make build-macos-universal
```

**Intel (x86_64):**
```bash
GOOS=darwin GOARCH=amd64 go build \
  -ldflags="-s -w -X main.version=$(git describe --tags --always --dirty)" \
  -o dist/mpv-manager-darwin-x86_64 ./cmd/mpv-manager
```

**Apple Silicon (arm64):**
```bash
GOOS=darwin GOARCH=arm64 go build \
  -ldflags="-s -w -X main.version=$(git describe --tags --always --dirty)" \
  -o dist/mpv-manager-darwin-arm64 ./cmd/mpv-manager
```

---

## Cross-Compilation

### Cross-Compile from Linux to Windows

```bash
# Install cross-compiler
sudo apt install mingw-w64

# Set cross-compilation environment
export CC=x86_64-w64-mingw32-gcc
export CXX=x86_64-w64-mingw32-g++
export GOOS=windows
export GOARCH=amd64

# Build
GOOS=windows GOARCH=amd64 GOAMD64=v2 go build \
  -ldflags="-s -w -H windowsgui" \
  -o dist/mpv-manager-win-x86_64.exe ./cmd/mpv-manager
```

### Cross-Compile from macOS to Linux

```bash
# Install cross-compiler
brew install x86_64-linux-gnu-gcc

# Set cross-compilation environment
export CC=x86_64-linux-gnu-gcc
export CXX=x86_64-linux-gnu-g++
export GOOS=linux
export GOARCH=amd64

# Build
GOOS=linux GOARCH=amd64 go build \
  -ldflags="-s -w -X main.version=$(git describe --tags --always --dirty)" \
  -o dist/mpv-manager-linux-x86_64 ./cmd/mpv-manager
```

### Cross-Compile from Linux to macOS

```bash
# Install macOS cross-compiler
sudo apt install golang-1.20-go-darwin-arm64

# Build for Apple Silicon
GOOS=darwin GOARCH=arm64 CC=o64-clang go build \
  -ldflags="-s -w -X main.version=$(git describe --tags --always --dirty)" \
  -o dist/mpv-manager-darwin-arm64 ./cmd/mpv-manager

# Build for Intel Macs
GOOS=darwin GOARCH=amd64 CC=o64-clang go build \
  -ldflags="-s -w -X main.version=$(git describe --tags --always --dirty)" \
  -o dist/mpv-manager-darwin-x86_64 ./cmd/mpv-manager
```

---

## Testing Builds

### Run Unit Tests

```bash
# Run all tests
go test ./...

# Run tests with verbose output
go test -v ./...

# Run tests with coverage
go test -cover ./...

# Run tests for specific package
go test ./pkg/web/...
```

### Run Integration Tests

```bash
# Run all integration tests
go test ./... -tags=integration

# Run specific integration test
go test ./pkg/installer/... -tags=integration
```

### Build Smoke Tests

```bash
# Test build on current platform
make build
./dist/mpv-manager --version

# Test binary execution
./dist/mpv-manager --help
```

### Platform-Specific Testing

**Windows:**
```powershell
# Test on Windows 10 and Windows 11
# Test with and without administrator privileges
# Test UAC elevation scenarios
```

**Linux:**
```bash
# Test on Ubuntu, Fedora, Arch
# Test with different package managers (apt, flatpak, snap)
# Test with and without sudo
```

**macOS:**
```bash
# Test on Intel Macs and Apple Silicon
# Test universal binary
# Test code signing
```

---

## Packaging

### Windows

**Create ZIP Archive:**
```powershell
# Compress installer and README
Compress-Archive -Path dist\mpv-manager-win-x86_64.exe -DestinationPath mpv-manager-windows-x86_64.zip
Compress-Archive -Path README.md -DestinationPath mpv-manager-windows-x86_64.zip
```

**Generate Checksums:**
```bash
# Generate BLAKE3 checksums
make checksums
```

### Linux

**Create TAR Archive:**
```bash
# Create tarball
tar -czf mpv-manager-linux-x86_64.tar.gz mpv-manager-linux-x86_64

# Create tarball with compression
tar -cJf mpv-manager-linux-x86_64.tar.xz mpv-manager-linux-x86_64
```

**Create Package:**
```bash
# Create Debian package
mkdir -p mpv-manager
cp dist/mpv-manager-linux-x86_64 mpv-manager/
cp mpv-manager/installer/linux/* mpv-manager/
tar -czf mpv-manager_1.0.0_amd64.deb -C mpv-manager .
```

### macOS

**Create DMG Disk Image:**
```bash
# Create DMG with macOS installer
mkdir -p dmg_root
cp dist/mpv-manager-darwin-arm64 dmg_root/
hdiutil create -srcfolder dmg_root -volname "mpv-manager" -ov mpv-manager-macos.dmg
```

**Universal Binary:**
```bash
# Create universal binary from both architectures
lipo -create -output mpv-manager-darwin-universal \
  mpv-manager-darwin-arm64 \
  mpv-manager-darwin-x86_64
```

---

## Release Procedure

### Version Bump

1. Update version in `cmd/mpv-manager/main.go`
2. Update version in `go.mod`
3. Commit changes with version message

### Tag Release

```bash
# Create annotated tag
git tag -a v1.2.3 -m "Release v1.2.3"

# Push tag
git push origin v1.2.3
```

### Generate Release Information

```bash
# Generate release JSON with versions and URLs
go run ./cmd/generate-info \
  --version $(git describe --tags --always --dirty) \
  --release-date $(date -u +"%Y-%m-%dT%H:%M:%SZ") \
  > internal/assets/releases.json
```

### Build Release Binaries

```bash
# Build all platforms
make build-all

# Generate all checksums
make checksums
```

### Create Release Assets

```bash
# Create release directory
mkdir -p release/v1.2.3

# Copy binaries
cp dist/* release/v1.2.3/

# Copy README and LICENSE
cp README.md release/v1.2.3/
cp LICENSE release/v1.2.3/

# Copy checksums
cp checksums/SHA256SUMS.txt release/v1.2.3/
cp checksums/BLAKE3SUMS.txt release/v1.2.3/
```

### Upload Release

1. Create GitHub release
2. Upload binaries to release
3. Upload checksums
4. Upload release notes
5. Update release documentation

---

## Deployment

### Production Deployment

**Binary Distribution:**

**Release Channels:**
- **Stable:** Latest stable release
- **Beta:** Feature-complete but not fully tested
- **Nightly:** Latest development build

**Update Mechanism:**
- Installer checks `releases.json` on startup
- Compares current version with latest available
- Displays update notification when new version available
- Supports auto-update with progress tracking

**Deployment Locations:**
- **Primary:** `https://gitgud.io/mike/mpv-manager/releases`
- **Fallback:** `https://gitgud.io/mike/mpv-manager/releases/download`
- **Mirrors:** (optional) CDN or cloud storage mirrors

### Package Manager Distribution

**Flatpak:**

```bash
# Build Flatpak manifest
flatpak-builder --repo=stable --install-deps-from=flathub \
  io.mpv.Mpv ./flatpak/com.github.mpv.Mpv.json

# Export to Flatpak repository
flatpak build-bundle --repo=stable --runtime=org.freedesktop.Platform/xorg-1.20 \
  io.mpv.Mpv ./mpv-manager/
```

**Snap:**

```bash
# Build Snap package
snapcraft --target=amd64

# Upload to Snap Store
snapcraft push --release=stable mpv-manager_amd64.snap
```

**Homebrew:**

```bash
# Create Homebrew formula
cat > mpv-manager.rb << 'EOF'
class InstallMpv < Formula
  url "https://gitgud.io/mike/mpv-manager/releases/download/v1.2.3/mpv-manager-macos-universal.tar.xz"
  sha256 "checksum-value"
  version "1.2.3"

  def install
    bin.install "mpv-manager"
  end
end
EOF

# Upload tap
brew tap-new username/mpv-manager
```

### Automated Build System

**CI/CD Pipeline:**

**Stages:**
1. **Linting** - Run golangci-lint
2. **Unit Tests** - Run all unit tests with coverage
3. **Integration Tests** - Run package integration tests
4. **Build** - Build for all platforms
5. **Package** - Create archives and checksums
6. **Upload** - Upload artifacts to storage
7. **Release** - Create GitHub release

**Trigger:** Push to main branch or manual trigger

**Build Matrix:**
| Platform | Architecture | Status |
|----------|-------------|--------|
| Windows | x86_64 | ✅ |
| Linux | x86_64 | ✅ |
| Linux | arm64 | ⏳ |
| macOS | x86_64 | ✅ |
| macOS | arm64 | ✅ |
| macOS | universal | ✅ |

---

## Quick Reference

### Common Build Commands

```bash
# Clean all builds
make clean

# Build current platform
make build

# Build all platforms
make build-all

# Build specific platform
make build-windows-x86_64
make build-linux-x86_64
make build-macos-arm64

# Generate checksums
make checksums

# Run tests
make test
```

### Environment Variables

| Variable | Purpose | Example |
|----------|-----------|---------|
| `GOOS` | Target OS | `windows`, `linux`, `darwin` |
| `GOARCH` | Target architecture | `amd64`, `arm64`, `386` |
| `GOAMD64` | CPU baseline (Windows) | `v2`, `v3`, `v4` |
| `CGO_ENABLED` | Enable/disable CGO | `0`, `1` |
| `LDFLAGS` | Linker flags | `-s -w -X main.version=...` |
| `TAGS` | Build tags | `netgo`, `osusergo`, `sqlite_omit_load_extension` |

### Build Targets

| Target | Description | Platforms |
|--------|-------------|------------|
| `build` | Build for current platform | All |
| `build-all` | Build for all platforms | All |
| `build-windows-x86_64` | Windows x86_64 | Windows |
| `build-linux-x86_64` | Linux x86_64 | Linux |
| `build-linux-arm64` | Linux ARM64 | Linux |
| `build-macos-x86_64` | macOS Intel | macOS |
| `build-macos-arm64` | macOS Apple Silicon | macOS |
| `build-macos-universal` | macOS universal binary | macOS |
| `test` | Run all tests | All |
| `clean` | Clean build artifacts | All |
| `checksums` | Generate checksums | All |
| `deps` | Install dependencies | All |

### Version Information

**Version Format:** `vMAJOR.MINOR.PATCH` (e.g., `v1.2.3`)

**Version Components:**
- **MAJOR:** Breaking changes or major features
- **MINOR:** New features in backwards-compatible manner
- **PATCH:** Bug fixes and minor improvements

**Build Version:** Generated from Git tags and commits
- Example: `v1.2.3-7-gabcdef1` (tag + commits)

---

## Troubleshooting Builds

### Build Fails

**Symptoms:**
- Compilation errors
- Linker errors
- Missing dependencies

**Solutions:**

1. **Clean Build Cache**
```bash
go clean -cache
make clean
```

2. **Update Dependencies**
```bash
go mod download
go mod tidy
```

3. **Check Go Version**
```bash
go version  # Should be 1.25 or later
```

4. **Check CGO (if enabled)**
```bash
# Verify CGO toolchain is installed
# Linux: gcc --version
# macOS: clang --version
# Windows: gcc --version
```

### Cross-Compilation Issues

**Common Problems:**

1. **Missing Cross-Compiler**
```bash
# Install cross-compiler
sudo apt install mingw-w64  # Windows on Linux
brew install x86_64-linux-gnu-gcc  # macOS to Linux
```

2. **Incorrect CC/CXX Flags**
```bash
# Set correct compiler and linker
export CC=x86_64-w64-mingw32-gcc
export CXX=x86_64-w64-mingw32-g++
```

3. **Wrong GOOS/GOARCH Combination**
```bash
# Verify valid combinations
# Windows: GOOS=windows, GOARCH=amd64/386
# Linux: GOOS=linux, GOARCH=amd64/arm64/386/riscv64
# macOS: GOOS=darwin, GOARCH=amd64/arm64
```

### Checksum Verification

**Generate BLAKE3 Checksums:**
```bash
make checksums

# View checksums
cat checksums/BLAKE3SUMS.txt
```

**Verify Downloads:**
```bash
# Generate checksum for downloaded file
b3sum mpv-manager-win-x86_64.exe

# Compare with release checksums
diff <(b3sum mpv-manager-win-x86_64.exe) checksums/BLAKE3SUMS.txt
```

---

## Security Considerations

### Code Signing

**Windows:**
```bash
# Sign binary with certificate (requires signtool)
signtool sign /f certificate.pfx /p password /t "http://timestamp.digicert.com" mpv-manager-win-x86_64.exe
```

**macOS:**
```bash
# Sign binary (requires Apple Developer account)
codesign --deep --force --verify --verbose --sign "Developer ID Application" mpv-manager-darwin-arm64
```

### Checksum Integrity

- Use BLAKE3 for integrity verification
- Publish checksums with releases
- Verify downloads before installation

### Dependency Management

- Pin Go module versions in `go.mod`
- Review dependencies for security updates
- Use `go mod download` with hashes for reproducibility

---

## Best Practices

### Build Performance

1. **Use Go Module Cache:** Speeds up subsequent builds
2. **Parallel Builds:** Build multiple platforms in parallel (if CI resources available)
3. **Minimal Dependencies:** Keep dependencies lean for faster builds
4. **Build Caching:** Cache Go build cache between builds

### Release Quality

1. **Comprehensive Testing:** Test all builds on target platforms
2. **Checksum Verification:** Verify all binaries with BLAKE3
3. **Documentation:** Include detailed release notes
4. **Rollback Plan:** Keep previous version available

### Deployment Safety

1. **Staging:** Deploy to staging environment first
2. **Gradual Rollout:** Release to subset of users first
3. **Monitoring:** Watch for issues after deployment
4. **Quick Rollback:** Revert to previous version if critical issues found

---

## Conclusion

This build and deployment guide provides comprehensive procedures for building, testing, packaging, and deploying MPV.Rocks Installer across all platforms. Follow these guidelines to ensure reliable, high-quality releases.

For additional information, see:
- [Session Summaries](docs/SESSION_SUMMARIES.md) - Detailed development sessions
- [Architecture](docs/ARCHITECTURE.md) - System architecture and design
- [Testing Guide](docs/TESTING.md) - Testing procedures and checklists
- [Troubleshooting](docs/TROUBLESHOOTING.md) - Common issues and solutions
