# Server Migration & Cleanup Attack Plan

## Overview
This document outlines a systematic approach to migrate applications from the old server to a new server while cleaning up redundant files, directories, and database tables.

---

## PHASE 1: ASSESSMENT & INVENTORY

### 1.1 Application Inventory

**Active Applications Identified:**
- ✅ **WHMCS Billing** (`/var/www/html/billing`) - Database: `whmcs`
- ✅ **Event Registration System** (`/var/www/html/wordpress6/wordpress/EP`) - Database: `eventreg`, `eventregdb`
- ✅ **Genealogy/Webtrees** (`/var/www/html/wordpress6/wordpress/EP/genealogy`) - Database: `genealogy`, `webtrees`
- ✅ **WordPress Sites**:
  - Main site (`/var/www/html/mainsite`) - Database: `mainsite`
  - WordPress6 (`/var/www/html/wordpress6`) - Database: `wordpress6`, `wordpressdb`
  - Pueblo Arabesque (`/var/www/html/puebloarabesque`) - Database: `wp-puebloarabesque`
  - Nina Nolte (`/var/www/html/ninanolte`) - Database: `nina`
- ✅ **YetiForce CRM** (`/var/www/html/yetiforce`) - Database: `yetiforce`
- ✅ **El Paraiso Frontend** (`/var/www/html/elparaiso-frontend`)
- ✅ **Accounts Receivable** - Database: `accounts_receivable`
- ✅ **Intranet** - Database: `intranet`
- ✅ **Gym Management** - Database: `gymmanagement`

**Potentially Unused:**
- ⚠️ **Node.js App** (`009-devnodejs_scala4.conf`) - Needs verification
- ⚠️ **Old Databases**: `oldchatthing`, `olddoorman`, `oldfriend`, `oldfriendchat` - Likely unused

### 1.2 Domain Inventory

**Apache Virtual Hosts Found:**
- `004-billing` (WHMCS)
- `006-wordpress`, `003-wordpress2` (WordPress sites)
- `007-el-paraiso-backend`, `008-el-paraiso-frontend` (El Paraiso)
- `010-puebloarabesque` (Pueblo Arabesque)
- `011-el-paraiso-event-reg` (Event Registration)
- `009-devnodejs_scala4` (Node.js - verify if used)
- `002-frfly.ovh` (Verify if used)
- `005-friendly` (Verify if used)

### 1.3 Database Inventory

**Active Databases (likely in use):**
- `whmcs` - WHMCS billing system
- `eventreg`, `eventregdb` - Event registration
- `genealogy`, `webtrees` - Genealogy system
- `mainsite`, `wordpress6`, `wordpressdb`, `wp-puebloarabesque`, `nina` - WordPress sites
- `yetiforce` - CRM system
- `accounts_receivable` - AR system
- `intranet` - Intranet system
- `gymmanagement` - Gym management
- `frontend` - Frontend database
- `el_paraiso`, `el_paraiso_backup` - El Paraiso databases

**Potentially Unused/Old Databases:**
- `oldchatthing` - Old chat system
- `olddoorman` - Old doorman system
- `oldfriend`, `oldfriendchat` - Old friend/chat systems
- `CSV_DB`, `ODS_DB` - Possibly temporary/import databases
- `presence` - Verify usage
- `Scala4` - Verify usage

---

## PHASE 2: PLANNING & PRIORITIZATION

### 2.1 Migration Priority Order

**Priority 1 - Critical Business Applications:**
1. **WHMCS Billing** (Revenue critical)
2. **Event Registration System** (Active user system)
3. **Main WordPress Site** (Primary website)

**Priority 2 - Important Applications:**
4. **Genealogy/Webtrees** (If actively used)
5. **El Paraiso Systems** (Backend + Frontend + Event Reg)
6. **Accounts Receivable** (Financial system)

**Priority 3 - Secondary Applications:**
7. **YetiForce CRM** (If actively used)
8. **Other WordPress Sites** (Pueblo Arabesque, Nina Nolte)
9. **Intranet** (If actively used)
10. **Gym Management** (If actively used)

**Priority 4 - Verify Before Migration:**
11. **Node.js Application** (Verify if used)
12. **Other domains** (frfly.ovh, friendly - verify usage)

### 2.2 Pre-Migration Checklist

For each application, document:
- [ ] Current directory location
- [ ] Database name(s) and size
- [ ] Apache virtual host configuration
- [ ] SSL certificates
- [ ] Dependencies (PHP version, extensions, etc.)
- [ ] Cron jobs
- [ ] File permissions
- [ ] Environment variables/config files
- [ ] Backup strategy

---

## PHASE 3: MIGRATION PROCESS (Application by Application)

### 3.1 Migration Template for Each Application

**Step 1: Pre-Migration**
```bash
# 1. Create backup
tar -czf /backup/[app-name]-$(date +%Y%m%d).tar.gz /var/www/html/[app-directory]
mysqldump -u admin -p [database-name] > /backup/[database-name]-$(date +%Y%m%d).sql

# 2. Document configuration
cp /etc/apache2/sites-available/[vhost].conf /backup/[vhost]-$(date +%Y%m%d).conf
```

**Step 2: New Server Setup**
```bash
# 1. Create directory structure
mkdir -p /var/www/html/[app-directory]

# 2. Copy files (use rsync for efficiency)
rsync -avz --progress user@old-server:/var/www/html/[app-directory]/ /var/www/html/[app-directory]/

# 3. Create database
mysql -u root -p -e "CREATE DATABASE [database-name] CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"

# 4. Import database
mysql -u root -p [database-name] < /backup/[database-name]-$(date +%Y%m%d).sql

# 5. Copy Apache config and adapt for new server
# 6. Update database credentials in config files
# 7. Set proper file permissions
```

**Step 3: Testing**
- [ ] Test application functionality
- [ ] Verify database connections
- [ ] Test SSL certificates
- [ ] Verify cron jobs (if applicable)
- [ ] Test file uploads/downloads
- [ ] Verify email functionality

**Step 4: DNS Cutover**
- [ ] Update DNS records to point to new server
- [ ] Monitor for issues
- [ ] Keep old server running for 48 hours as backup

**Step 5: Post-Migration**
- [ ] Verify all functionality
- [ ] Update monitoring/backup systems
- [ ] Document new server details

### 3.2 Application-Specific Notes

#### WHMCS Billing
- **Critical**: License key, encryption hash
- **Database**: `whmcs`
- **Config**: `/var/www/html/billing/configuration.php`
- **Special**: ionCube Loader required, cron jobs critical

#### Event Registration System
- **Database**: `eventreg`, `eventregdb`
- **Config**: Multiple PHP config files
- **Special**: Check for hardcoded paths

#### Genealogy/Webtrees
- **Database**: `genealogy`, `webtrees`
- **Config**: `.env` or config files
- **Special**: Media files, GEDCOM files

#### WordPress Sites
- **Standard WordPress migration**
- **Update**: `wp-config.php` with new database credentials
- **Check**: Upload directories, themes, plugins
- **Update**: Site URLs in database if domain changes

---

## PHASE 4: CLEANUP PROCESS

### 4.1 File & Directory Cleanup

**Step 1: Identify Unused Directories**
```bash
# Find large directories
du -sh /var/www/html/* | sort -h

# Find directories not accessed in 6+ months
find /var/www/html -type d -atime +180 -ls

# Find empty directories
find /var/www/html -type d -empty
```

**Step 2: Identify Unused Files**
```bash
# Find large files
find /var/www/html -type f -size +100M -ls

# Find old backup files
find /var/www/html -name "*.tar.gz" -o -name "*.zip" -o -name "*backup*" -ls

# Find old log files
find /var/www/html -name "*.log" -atime +90 -ls

# Find node_modules (if Node.js app is unused)
find /var/www/html -type d -name "node_modules" -exec du -sh {} \;
```

**Step 3: Cleanup Script Template**
```bash
#!/bin/bash
# cleanup-unused-files.sh

BACKUP_DIR="/backup/cleanup-$(date +%Y%m%d)"
mkdir -p "$BACKUP_DIR"

# 1. Backup before deletion
echo "Creating backup..."
tar -czf "$BACKUP_DIR/unused-files.tar.gz" [files-to-delete]

# 2. Remove old backups (older than 1 year)
find /var/www/html -name "*.tar.gz" -mtime +365 -delete
find /var/www/html -name "*.zip" -mtime +365 -delete

# 3. Remove old log files (older than 90 days)
find /var/www/html -name "*.log" -mtime +90 -delete

# 4. Remove empty directories
find /var/www/html -type d -empty -delete

# 5. Remove node_modules if Node.js app is unused
# Uncomment if confirmed unused:
# find /var/www/html -type d -name "node_modules" -exec rm -rf {} +
```

### 4.2 Database Cleanup

**Step 1: Identify Unused Databases**
```sql
-- List all databases with sizes
SELECT 
    table_schema AS 'Database',
    ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)'
FROM information_schema.tables
GROUP BY table_schema
ORDER BY SUM(data_length + index_length) DESC;
```

**Step 2: Identify Unused Tables**
```sql
-- For each database, find tables with no recent activity
-- Check last update times (if available)
SELECT 
    TABLE_NAME,
    TABLE_ROWS,
    ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2) AS 'Size (MB)',
    UPDATE_TIME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = '[database-name]'
ORDER BY UPDATE_TIME ASC;
```

**Step 3: Database Cleanup Script**
```bash
#!/bin/bash
# cleanup-databases.sh

# 1. Backup before deletion
BACKUP_DIR="/backup/db-cleanup-$(date +%Y%m%d)"
mkdir -p "$BACKUP_DIR"

# 2. Backup old/unused databases before deletion
mysqldump -u admin -p oldchatthing > "$BACKUP_DIR/oldchatthing.sql"
mysqldump -u admin -p olddoorman > "$BACKUP_DIR/olddoorman.sql"
mysqldump -u admin -p oldfriend > "$BACKUP_DIR/oldfriend.sql"
mysqldump -u admin -p oldfriendchat > "$BACKUP_DIR/oldfriendchat.sql"

# 3. Drop unused databases (ONLY after verification!)
# mysql -u admin -p -e "DROP DATABASE IF EXISTS oldchatthing;"
# mysql -u admin -p -e "DROP DATABASE IF EXISTS olddoorman;"
# mysql -u admin -p -e "DROP DATABASE IF EXISTS oldfriend;"
# mysql -u admin -p -e "DROP DATABASE IF EXISTS oldfriendchat;"
```

**Step 4: Table Cleanup (Within Active Databases)**
```sql
-- Example: Find and remove old/unused tables
-- 1. List all tables
SHOW TABLES;

-- 2. Check table sizes
SELECT 
    TABLE_NAME,
    ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2) AS 'Size (MB)'
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = '[database-name]'
ORDER BY (DATA_LENGTH + INDEX_LENGTH) DESC;

-- 3. Look for backup/old tables (common patterns)
SELECT TABLE_NAME 
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = '[database-name]' 
AND (
    TABLE_NAME LIKE '%backup%' 
    OR TABLE_NAME LIKE '%old%' 
    OR TABLE_NAME LIKE '%temp%'
    OR TABLE_NAME LIKE '%_bak'
    OR TABLE_NAME LIKE '%_old'
);

-- 4. Before dropping, backup:
-- mysqldump -u admin -p [database] [table-name] > backup.sql

-- 5. Drop table (ONLY after verification!)
-- DROP TABLE IF EXISTS [table-name];
```

### 4.3 Apache Configuration Cleanup

**Step 1: Identify Unused Virtual Hosts**
```bash
# List all enabled sites
ls -la /etc/apache2/sites-enabled/

# Check which domains actually resolve
for conf in /etc/apache2/sites-available/*.conf; do
    domain=$(grep -i "ServerName" "$conf" | awk '{print $2}')
    echo "Checking $domain..."
    host "$domain" 2>/dev/null || echo "  ⚠️  $domain does not resolve"
done
```

**Step 2: Disable Unused Virtual Hosts**
```bash
# Disable unused virtual hosts
sudo a2dissite [unused-vhost].conf
sudo systemctl reload apache2
```

---

## PHASE 5: VERIFICATION & TESTING

### 5.1 Post-Migration Checklist

For each migrated application:
- [ ] Application loads correctly
- [ ] Database connections work
- [ ] File uploads/downloads work
- [ ] Email functionality works
- [ ] SSL certificates valid
- [ ] Cron jobs running (if applicable)
- [ ] Backups configured
- [ ] Monitoring set up

### 5.2 Cleanup Verification

- [ ] Verify no critical files were deleted
- [ ] Check application logs for errors
- [ ] Verify database integrity
- [ ] Check disk space freed
- [ ] Document what was removed

---

## PHASE 6: FINAL CLEANUP (After Migration Complete)

### 6.1 Old Server Cleanup

**Only after all applications are migrated and verified:**

1. **Final Backup**
   ```bash
   # Create complete server backup
   tar -czf /backup/old-server-complete-$(date +%Y%m%d).tar.gz /var/www/html
   ```

2. **Remove Migrated Applications**
   ```bash
   # Remove directories (after verification)
   rm -rf /var/www/html/[migrated-app]
   ```

3. **Clean Up Databases**
   ```bash
   # Drop migrated databases (after verification)
   mysql -u admin -p -e "DROP DATABASE [database-name];"
   ```

4. **Remove Apache Configs**
   ```bash
   # Remove virtual host configs
   rm /etc/apache2/sites-available/[vhost].conf
   rm /etc/apache2/sites-available/[vhost]-le-ssl.conf
   ```

---

## TOOLS & SCRIPTS TO CREATE

### 1. Application Inventory Script
```bash
#!/bin/bash
# inventory-applications.sh
# Lists all applications, their locations, databases, and configs
```

### 2. Database Analysis Script
```bash
#!/bin/bash
# analyze-databases.sh
# Lists all databases, sizes, table counts, and last activity
```

### 3. File Cleanup Script
```bash
#!/bin/bash
# cleanup-files.sh
# Identifies and optionally removes unused files
```

### 4. Migration Script Template
```bash
#!/bin/bash
# migrate-app.sh [app-name]
# Standardized migration process for each application
```

---

## RISK MITIGATION

1. **Always backup before deletion**
2. **Test on staging/new server before DNS cutover**
3. **Keep old server running for 48-72 hours after migration**
4. **Document everything**
5. **Test each application thoroughly before moving to next**
6. **Have rollback plan for each application**

---

## ESTIMATED TIMELINE

- **Phase 1 (Assessment)**: 1-2 days
- **Phase 2 (Planning)**: 1 day
- **Phase 3 (Migration)**: 1-2 weeks (depending on app complexity)
- **Phase 4 (Cleanup)**: 2-3 days
- **Phase 5 (Verification)**: 2-3 days
- **Phase 6 (Final Cleanup)**: 1 day

**Total: 3-4 weeks** (allowing for testing and issues)

---

## NEXT STEPS

1. Review this plan
2. Prioritize applications based on business needs
3. Start with Phase 1 - create detailed inventory
4. Begin migration with Priority 1 applications
5. Test thoroughly before moving to next application

