#!/bin/bash
# Universal Project Backup Setup Template
# Run this in any new project directory to set up zero-data-loss protection
# Usage: cd /path/to/project && ~/.clawdbot/workspace/PROJECT-BACKUP-TEMPLATE.sh

set -e

PROJECT_NAME="$(basename "$(pwd)")"
GITHUB_USER="${1:-BusyBee3333}"
RCLONE_REMOTE="${2:-do-spaces}"
REMOTE_BACKUP_DIR="${3:-projects}"

echo "=========================================="
echo "PROJECT BACKUP SETUP"
echo "=========================================="
echo "Project: $PROJECT_NAME"
echo "GitHub user: $GITHUB_USER"
echo "Cloud remote: $RCLONE_REMOTE"
echo ""

# ========================================
# LAYER 1: Git + GitHub (Instant Code Sync)
# ========================================

echo "📦 Setting up Git + GitHub..."
echo "----------------------------------------"

if [[ -d ".git" ]]; then
  echo "   ⚠️  Git repository already exists"
else
  echo "   [1/3] Initializing git repository..."
  git init
  git branch -M main
  echo "   ✓ Initialized"
fi

# Create .gitignore if not exists
if [[ ! -f ".gitignore" ]]; then
  echo "   [2/3] Creating .gitignore..."
  cat > .gitignore <<'EOF'
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
*.egg-info/
dist/
build/
.venv/
venv/
.venv311/

# Environment variables (NEVER commit secrets)
.env
.env.local
.env.*.local

# Database dumps
*.sql
*.db
*.sqlite

# Logs
*.log

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# macOS
.DS_Store
.AppleDouble
.LSOverride
._*

# Backup files
backup-*
backup-*
*.bak
*.backup

# Node
node_modules/

# Test artifacts
.pytest_cache/
.coverage
htmlcov/
EOF
  echo "   ✓ Created .gitignore"
else
  echo "   [2/3] .gitignore already exists"
fi

# Check if GitHub repo exists
if gh repo view "$PROJECT_NAME" --json name,owner &>/dev/null; then
  echo "   [3/3] GitHub repo already exists"
  if ! git remote | grep -q "^origin$"; then
    git remote add origin "https://github.com/$GITHUB_USER/$PROJECT_NAME.git"
    git branch -M main
    git remote set-url origin "https://github.com/$GITHUB_USER/$PROJECT_NAME.git"
  fi
else
  echo "   [3/3] Creating GitHub repository..."
  read -p "   Make repo private? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    gh repo create "$PROJECT_NAME" --private --source=. --remote=origin
  else
    gh repo create "$PROJECT_NAME" --public --source=. --remote=origin
  fi
  echo "   ✓ Created: https://github.com/$GITHUB_USER/$PROJECT_NAME"
fi

echo ""

# ========================================
# LAYER 2: Cloud Backup (Daily)
# ========================================

echo "☁️  Setting up Cloud Backup..."
echo "----------------------------------------"

# Create backup script for this project
cat > ".backup_project.sh" <<EOF
#!/bin/bash
# Backup script for $PROJECT_NAME
# Run this manually or add to crontab

set -e

BACKUP_NAME="$PROJECT_NAME-backup-\$(date +%Y%m%d-%H%M%S)"
BACKUP_DIR="\$HOME/.clawdbot/workspace/backups/\$BACKUP_NAME"
REMOTE="$RCLONE_REMOTE"
REMOTE_DIR="$REMOTE_BACKUP_DIR"

mkdir -p "\$BACKUP_DIR"

echo "=========================================="
echo "BACKUP: $PROJECT_NAME"
echo "=========================================="
echo "Local: \$BACKUP_DIR"
echo "Cloud: \$REMOTE:\$REMOTE_DIR/\$BACKUP_NAME"
echo ""

# Backup project files
echo "[1/4] Backing up project files..."
rsync -av --exclude='.git' --exclude='__pycache__' --exclude='.venv' --exclude='venv' --exclude='node_modules' --exclude='*.log' --exclude='.DS_Store' . "\$BACKUP_DIR/project/"
echo "   ✓ Project files backed up"

# Backup configs if they exist
echo "[2/4] Backing up environment files..."
if [[ -f ".env" ]]; then
  cp .env "\$BACKUP_DIR/env/"
  echo "   ✓ .env backed up"
else
  echo "   ⚠️  No .env file found"
fi

# Backup databases (if any)
echo "[3/4] Checking for databases..."
# Add your database backup commands here
# Example: pg_dump \$DB_NAME > "\$BACKUP_DIR/db.sql"

# Create checksums
echo "[4/4] Creating checksums..."
cd "\$BACKUP_DIR"
find . -type f -exec shasum {} \; > "\$BACKUP_DIR/sha256-checksums.txt"
echo "   ✓ Checksums created"

echo ""
echo "Uploading to cloud..."
rclone sync "\$BACKUP_DIR/" "\$REMOTE:\$REMOTE_DIR/\$BACKUP_NAME/" --progress

echo ""
echo "=========================================="
echo "BACKUP COMPLETE"
echo "=========================================="
echo ""
echo "Cloud location: \$REMOTE:\$REMOTE_DIR/\$BACKUP_NAME/"
EOF

chmod +x ".backup_project.sh"

echo "   ✓ Created .backup_project.sh"
echo ""

# Add to crontab?
echo "   📅 Want to add daily automatic backup to crontab?"
read -p "   Time (hour, 0-23)? [2] " CRON_HOUR
CRON_HOUR=${CRON_HOUR:-2}

read -p "   Add to crontab for daily backup at $CRON_HOUR:00? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
  CRON_LINE="0 $CRON_HOUR * * * cd $(pwd) && ./.backup_project.sh >> ~/.clawdbot/workspace/backups.log 2>&1"
  (crontab -l 2>/dev/null; echo "$CRON_LINE") | crontab -
  echo "   ✓ Added to crontab"
else
  echo "   ⚠️  Skipped crontab addition"
fi

echo ""

# ========================================
# LAYER 3: 1Password Setup (Secrets)
# ========================================

echo "🔐 1Password Setup"
echo "----------------------------------------"
echo "   Store these secrets in 1Password:"
echo "   - Project name: $PROJECT_NAME"
echo "   - Environment variables (if any in .env)"
echo "   - API keys, tokens, credentials"
echo ""

if [[ -f ".env" ]]; then
  echo "   ⚠️  .env file detected — add to 1Password:"
  cat .env
  echo ""
fi

# ========================================
# LAYER 4: Restore Instructions
# ========================================

echo "📋 Restore Instructions"
echo "----------------------------------------"

cat > ".RESTORE.md" <<EOF
# $PROJECT_NAME - Restore Guide

## Quick Restore from GitHub

\`\`\`bash
# Clone the repository
git clone https://github.com/$GITHUB_USER/$PROJECT_NAME.git
cd $PROJECT_NAME

# Install dependencies (add project-specific commands)
# Example: pip install -r requirements.txt
\`\`\`

## Restore from Cloud Backup

\`\`\`bash
# List available backups
rclone ls $RCLONE_REMOTE:$REMOTE_BACKUP_DIR/

# Download and extract a backup
rclone sync $RCLONE_REMOTE:$REMOTE_BACKUP_DIR/PROJECT-BACKUP-DATE/ ./

# Restore environment variables from .env
# (Check 1Password for secrets if missing)
\`\`\`

## Restore Database (if applicable)

\`\`\`bash
# Restore from SQL dump
psql -U USER -D DATABASE < backup.sql
\`\`\`

## Verify Everything Works

\`\`\`bash
# Run tests
pytest

# Start services
# Add project-specific commands
\`\`\`

---

**Last updated:** $(date)
EOF

echo "   ✓ Created .RESTORE.md"
echo ""

# ========================================
# Summary
# ========================================

echo "=========================================="
echo "✅ SETUP COMPLETE"
echo "=========================================="
echo ""
echo "📦 Git + GitHub:"
echo "   Repo: https://github.com/$GITHUB_USER/$PROJECT_NAME"
echo "   Commit often with: git add . && git commit -m 'msg' && git push"
echo ""
echo "☁️  Cloud Backup:"
echo "   Script: .backup_project.sh"
echo "   Run manually: ./.backup_project.sh"
echo "   Remote: $RCLONE_REMOTE:$REMOTE_BACKUP_DIR/"
echo ""
echo "🔐 Secrets:"
echo "   Add .env contents to 1Password"
echo "   Never commit .env to git"
echo ""
echo "📋 Restore:"
echo "   See .RESTORE.md for instructions"
echo ""
echo "💛 Buba's tips:"
echo "   - Commit and push daily"
echo "   - Check backups weekly"
echo "   - Test restore quarterly"
echo ""
