-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathupgrade.sh
More file actions
executable file
·769 lines (651 loc) · 25.7 KB
/
upgrade.sh
File metadata and controls
executable file
·769 lines (651 loc) · 25.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
#!/bin/bash
# =====================================================
# CODEHERO - Upgrade Script (Modular)
# =====================================================
# Usage:
# sudo ./upgrade.sh # Interactive mode
# sudo ./upgrade.sh -y # Auto-confirm all
# sudo ./upgrade.sh --dry-run # Show what would be done
# =====================================================
# Note: We don't use 'set -e' to allow graceful error handling
# Each critical step checks for errors explicitly
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BLUE='\033[0;34m'
NC='\033[0m'
# Paths
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_DIR="/opt/codehero"
# Safety check: SOURCE must not be same as INSTALL
if [ "$SOURCE_DIR" = "$INSTALL_DIR" ]; then
echo -e "${RED}ERROR: Cannot run upgrade from ${INSTALL_DIR}${NC}"
echo ""
echo "You extracted the zip to the wrong location!"
echo ""
echo "Correct procedure:"
echo " 1. cd /root"
echo " 2. unzip codehero-X.Y.Z.zip"
echo " 3. cd codehero"
echo " 4. sudo ./upgrade.sh"
echo ""
exit 1
fi
BACKUP_DIR="/var/backups/codehero"
CONFIG_DIR="/etc/codehero"
UPGRADES_DIR="${SOURCE_DIR}/upgrades"
APPLIED_FILE="${CONFIG_DIR}/applied_upgrades"
# Options
DRY_RUN=false
AUTO_YES=false
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--dry-run) DRY_RUN=true; shift ;;
-y|--yes) AUTO_YES=true; shift ;;
-h|--help)
echo "Usage: sudo ./upgrade.sh [OPTIONS]"
echo ""
echo "Options:"
echo " -y, --yes Auto-confirm all prompts"
echo " --dry-run Show what would be done without making changes"
echo " -h, --help Show this help message"
exit 0
;;
*) echo -e "${RED}Unknown option: $1${NC}"; exit 1 ;;
esac
done
# Functions
log_info() { echo -e "${CYAN}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
confirm() {
if [ "$AUTO_YES" = true ]; then return 0; fi
read -p "$1 [y/N]: " response
case "$response" in [yY][eE][sS]|[yY]) return 0 ;; *) return 1 ;; esac
}
version_compare() {
# Returns: 0 if equal, 1 if $1 > $2, 2 if $1 < $2
if [ "$1" = "$2" ]; then return 0; fi
local IFS=.
local i ver1=($1) ver2=($2)
for ((i=0; i<${#ver1[@]}; i++)); do
if [ -z "${ver2[i]}" ]; then return 1; fi
if ((10#${ver1[i]} > 10#${ver2[i]})); then return 1; fi
if ((10#${ver1[i]} < 10#${ver2[i]})); then return 2; fi
done
return 0
}
version_gt() {
# Returns 0 if $1 > $2
set +e; version_compare "$1" "$2"; local result=$?; set -e
[ $result -eq 1 ]
}
version_gte() {
# Returns 0 if $1 >= $2
set +e; version_compare "$1" "$2"; local result=$?; set -e
[ $result -eq 0 ] || [ $result -eq 1 ]
}
get_db_credentials() {
source ${CONFIG_DIR}/system.conf 2>/dev/null || {
log_error "Cannot read ${CONFIG_DIR}/system.conf"
exit 1
}
DB_USER="${DB_USER:-claude_user}"
DB_PASS="${DB_PASSWORD:-claudepass123}"
DB_NAME="${DB_NAME:-claude_knowledge}"
}
run_sql() {
mysql -u "${DB_USER}" -p"${DB_PASS}" "${DB_NAME}" -e "$1" 2>/dev/null
}
run_sql_file() {
mysql -u "${DB_USER}" -p"${DB_PASS}" "${DB_NAME}" < "$1" 2>/dev/null
}
# =====================================================
# MAIN SCRIPT
# =====================================================
echo -e "${GREEN}"
echo "╔═══════════════════════════════════════════════════════════╗"
echo "║ CODEHERO - Upgrade Script ║"
echo "╚═══════════════════════════════════════════════════════════╝"
echo -e "${NC}"
if [ "$DRY_RUN" = true ]; then
echo -e "${BLUE}>>> DRY-RUN MODE - No changes will be made <<<${NC}"
echo ""
fi
# Check root
if [ "$EUID" -ne 0 ]; then
log_error "Please run as root or with sudo"
exit 1
fi
# Check if installation exists
if [ ! -d "$INSTALL_DIR" ]; then
log_error "CodeHero is not installed at $INSTALL_DIR"
log_info "Please run setup.sh for fresh installation"
exit 1
fi
# Get versions
NEW_VERSION=$(cat "${SOURCE_DIR}/VERSION" 2>/dev/null || echo "0.0.0")
CURRENT_VERSION=$(cat "${INSTALL_DIR}/VERSION" 2>/dev/null || echo "0.0.0")
echo -e "Current version: ${YELLOW}${CURRENT_VERSION}${NC}"
echo -e "New version: ${GREEN}${NEW_VERSION}${NC}"
echo ""
# Validate versions match zip filename (detect wrong download)
ZIP_NAME=$(basename "$(dirname "${SOURCE_DIR}")" 2>/dev/null)
if [[ "$ZIP_NAME" =~ codehero-([0-9]+\.[0-9]+\.[0-9]+) ]]; then
ZIP_VERSION="${BASH_REMATCH[1]}"
if [ "$ZIP_VERSION" != "$NEW_VERSION" ]; then
log_warning "Mismatch detected!"
log_warning "Zip filename suggests version: $ZIP_VERSION"
log_warning "But VERSION file contains: $NEW_VERSION"
log_warning "You may have downloaded the wrong file."
if ! confirm "Continue anyway?"; then
exit 1
fi
fi
fi
# Compare versions
set +e
version_compare "$NEW_VERSION" "$CURRENT_VERSION"
VCOMP=$?
set -e
case $VCOMP in
0)
log_warning "Versions are the same. Nothing to upgrade."
if ! confirm "Continue anyway?"; then exit 0; fi
;;
2)
log_warning "New version ($NEW_VERSION) is older than current ($CURRENT_VERSION)"
log_warning "This will DOWNGRADE your installation."
if ! confirm "Downgrade?"; then exit 0; fi
;;
esac
# =====================================================
# FIND PENDING UPGRADES
# =====================================================
echo -e "${CYAN}=== Upgrade Summary ===${NC}"
echo ""
# Initialize applied upgrades file
mkdir -p "${CONFIG_DIR}"
touch "${APPLIED_FILE}"
# Find upgrade scripts to run
log_info "Upgrade scripts to apply:"
PENDING_UPGRADES=()
if [ -d "$UPGRADES_DIR" ]; then
for script in $(ls -1 "${UPGRADES_DIR}"/*.sh 2>/dev/null | grep -v '_always.sh' | sort -V); do
script_name=$(basename "$script" .sh)
# Skip if already applied
if grep -qx "$script_name" "${APPLIED_FILE}" 2>/dev/null; then
continue
fi
# Skip if version is older than or equal to current
if version_gte "$CURRENT_VERSION" "$script_name" 2>/dev/null; then
continue
fi
# Skip if version is newer than target
if version_gt "$script_name" "$NEW_VERSION" 2>/dev/null; then
continue
fi
echo " [PENDING] $script_name"
PENDING_UPGRADES+=("$script")
done
fi
if [ ${#PENDING_UPGRADES[@]} -eq 0 ]; then
echo " (no pending upgrade scripts)"
fi
echo ""
# Find database migrations
get_db_credentials
# Ensure schema_migrations table exists
if [ "$DRY_RUN" = false ]; then
run_sql "CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(20) PRIMARY KEY,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);" 2>/dev/null || true
fi
log_info "Database migrations to apply:"
MIGRATIONS_DIR="${SOURCE_DIR}/database/migrations"
PENDING_MIGRATIONS=()
# Extract version from migration filename (e.g., 2.72.0_auto_review.sql → 2.72.0)
extract_migration_version() {
local name="$1"
echo "$name" | grep -oE '^[0-9]+\.[0-9]+\.[0-9]+' || echo ""
}
if [ -d "$MIGRATIONS_DIR" ]; then
for migration in $(ls -1 "${MIGRATIONS_DIR}"/*.sql 2>/dev/null | sort -V); do
migration_name=$(basename "$migration" .sql)
migration_version=$(extract_migration_version "$migration_name")
# Skip if no version found in filename
if [ -z "$migration_version" ]; then
echo " [SKIP] $migration_name (no version in filename)"
continue
fi
# Skip if migration version <= current version (already should be applied)
if version_gte "$CURRENT_VERSION" "$migration_version" 2>/dev/null; then
continue
fi
# Skip if migration version > new version (future migration)
if version_gt "$migration_version" "$NEW_VERSION" 2>/dev/null; then
continue
fi
# Skip if already applied
applied=$(run_sql "SELECT version FROM schema_migrations WHERE version='${migration_name}';" 2>/dev/null | tail -1)
if [ -n "$applied" ]; then
continue
fi
echo " [PENDING] $migration_name (v$migration_version)"
PENDING_MIGRATIONS+=("$migration")
done
fi
if [ ${#PENDING_MIGRATIONS[@]} -eq 0 ]; then
echo " (no pending migrations)"
fi
echo ""
# Dry-run ends here
if [ "$DRY_RUN" = true ]; then
echo -e "${BLUE}=== Dry-run complete ===${NC}"
echo "Run without --dry-run to apply changes."
exit 0
fi
# Confirm upgrade
if ! confirm "Proceed with upgrade?"; then
log_info "Upgrade cancelled."
exit 0
fi
echo ""
echo -e "${CYAN}=== Starting Upgrade ===${NC}"
echo ""
# =====================================================
# STEP 1: CREATE BACKUP
# =====================================================
BACKUP_NAME="codehero-${CURRENT_VERSION}-$(date +%Y%m%d_%H%M%S)"
log_info "Creating backup: ${BACKUP_DIR}/${BACKUP_NAME}.tar.gz"
mkdir -p "$BACKUP_DIR"
tar -czf "${BACKUP_DIR}/${BACKUP_NAME}.tar.gz" -C /opt codehero 2>/dev/null
log_success "Backup created"
# =====================================================
# STEP 2: STOP DAEMON
# =====================================================
log_info "Stopping daemon..."
systemctl stop codehero-daemon 2>/dev/null || true
sleep 1
log_success "Daemon stopped"
# =====================================================
# STEP 3: COPY FILES
# =====================================================
log_info "Copying files..."
# Web app
if [ -d "${SOURCE_DIR}/web" ]; then
cp -r "${SOURCE_DIR}/web/"* "${INSTALL_DIR}/web/" 2>/dev/null || true
echo " Copied web files"
fi
# Scripts
if [ -d "${SOURCE_DIR}/scripts" ]; then
cp "${SOURCE_DIR}/scripts/"*.py "${INSTALL_DIR}/scripts/" 2>/dev/null || true
cp "${SOURCE_DIR}/scripts/"*.sh "${INSTALL_DIR}/scripts/" 2>/dev/null || true
chmod +x "${INSTALL_DIR}/scripts/"*.sh 2>/dev/null || true
echo " Copied scripts"
fi
# Docs
if [ -d "${SOURCE_DIR}/docs" ]; then
mkdir -p "${INSTALL_DIR}/docs"
cp -r "${SOURCE_DIR}/docs/"* "${INSTALL_DIR}/docs/" 2>/dev/null || true
echo " Copied docs"
fi
# Config files
if [ -d "${SOURCE_DIR}/config" ]; then
mkdir -p "${INSTALL_DIR}/config"
cp "${SOURCE_DIR}/config/"*.md "${INSTALL_DIR}/config/" 2>/dev/null || true
cp "${SOURCE_DIR}/config/"*.json "${INSTALL_DIR}/config/" 2>/dev/null || true
cp "${SOURCE_DIR}/config/"*.conf "${INSTALL_DIR}/config/" 2>/dev/null || true
cp "${SOURCE_DIR}/config/"*.md "${CONFIG_DIR}/" 2>/dev/null || true
cp "${SOURCE_DIR}/config/"*.json "${CONFIG_DIR}/" 2>/dev/null || true
cp "${SOURCE_DIR}/config/"*.conf "${CONFIG_DIR}/" 2>/dev/null || true
echo " Copied config files"
fi
# Language-specific context files
if [ -d "${SOURCE_DIR}/config/contexts" ]; then
mkdir -p "${INSTALL_DIR}/config/contexts"
cp -r "${SOURCE_DIR}/config/contexts/"* "${INSTALL_DIR}/config/contexts/" 2>/dev/null || true
echo " Copied language contexts (php, python, node, etc.)"
fi
# Upgrades directory
if [ -d "${SOURCE_DIR}/upgrades" ]; then
mkdir -p "${INSTALL_DIR}/upgrades"
cp "${SOURCE_DIR}/upgrades/"*.sh "${INSTALL_DIR}/upgrades/" 2>/dev/null || true
cp "${SOURCE_DIR}/upgrades/"*.md "${INSTALL_DIR}/upgrades/" 2>/dev/null || true
chmod +x "${INSTALL_DIR}/upgrades/"*.sh 2>/dev/null || true
echo " Copied upgrades"
fi
# VERSION, CHANGELOG, and documentation
cp "${SOURCE_DIR}/VERSION" "${INSTALL_DIR}/"
cp "${SOURCE_DIR}/CHANGELOG.md" "${INSTALL_DIR}/" 2>/dev/null || true
cp "${SOURCE_DIR}/README.md" "${INSTALL_DIR}/" 2>/dev/null || true
cp "${SOURCE_DIR}/CLAUDE_OPERATIONS.md" "${INSTALL_DIR}/" 2>/dev/null || true
cp "${SOURCE_DIR}/CLAUDE_DEV_NOTES.md" "${INSTALL_DIR}/" 2>/dev/null || true
cp "${SOURCE_DIR}/CLAUDE.md" "${INSTALL_DIR}/" 2>/dev/null || true
log_success "Files copied"
# =====================================================
# STEP 3.5: ENSURE PYTHON DEPENDENCIES
# =====================================================
log_info "Checking Python dependencies..."
pip3 install --quiet --ignore-installed eventlet --break-system-packages 2>/dev/null || \
pip3 install --quiet --ignore-installed eventlet 2>/dev/null || true
log_success "Python dependencies OK"
# =====================================================
# STEP 4: RUN VERSION UPGRADE SCRIPTS
# =====================================================
if [ ${#PENDING_UPGRADES[@]} -gt 0 ]; then
log_info "Running upgrade scripts..."
for script in "${PENDING_UPGRADES[@]}"; do
script_name=$(basename "$script" .sh)
echo -n " Running $script_name... "
if bash "$script" 2>&1 | sed 's/^/ /'; then
echo "$script_name" >> "${APPLIED_FILE}"
echo -e "${GREEN}OK${NC}"
else
echo -e "${YELLOW}WARNING${NC}"
fi
done
log_success "Upgrade scripts completed"
fi
# Run _always.sh if exists
if [ -f "${UPGRADES_DIR}/_always.sh" ]; then
log_info "Running cleanup script..."
bash "${UPGRADES_DIR}/_always.sh" 2>&1 | sed 's/^/ /'
log_success "Cleanup completed"
fi
# =====================================================
# STEP 5: APPLY DATABASE MIGRATIONS
# =====================================================
if [ ${#PENDING_MIGRATIONS[@]} -gt 0 ]; then
log_info "Applying database migrations..."
for migration in "${PENDING_MIGRATIONS[@]}"; do
migration_name=$(basename "$migration" .sql)
echo -n " Applying $migration_name... "
if run_sql_file "$migration"; then
run_sql "INSERT INTO schema_migrations (version) VALUES ('${migration_name}');"
echo -e "${GREEN}OK${NC}"
else
echo -e "${RED}FAILED${NC}"
log_error "Migration failed: $migration_name"
log_info "Rolling back: starting services..."
systemctl start codehero-daemon 2>/dev/null || true
systemctl start codehero-web 2>/dev/null || true
exit 1
fi
done
log_success "All migrations applied"
fi
# =====================================================
# STEP 5.5: OPTIMIZE MYSQL SETTINGS
# =====================================================
log_info "Checking MySQL performance settings..."
# Apply runtime settings
mysql -u "${DB_USER}" -p"${DB_PASS}" -e "SET GLOBAL wait_timeout=300;" 2>/dev/null || true
mysql -u "${DB_USER}" -p"${DB_PASS}" -e "SET GLOBAL interactive_timeout=600;" 2>/dev/null || true
# Persist settings to config file
MYSQL_CONF="/etc/mysql/mysql.conf.d/mysqld.cnf"
if [ -f "$MYSQL_CONF" ]; then
# Ensure [mysqld] section exists (required for MySQL 8.0+)
if ! grep -q "^\[mysqld\]" "$MYSQL_CONF"; then
# Add [mysqld] before first non-comment option
sed -i '/^user[[:space:]]*=/i [mysqld]' "$MYSQL_CONF" 2>/dev/null || true
echo " Added missing [mysqld] section header"
fi
# Remove old settings if they exist
sed -i '/^wait_timeout=/d' "$MYSQL_CONF" 2>/dev/null || true
sed -i '/^interactive_timeout=/d' "$MYSQL_CONF" 2>/dev/null || true
sed -i '/^# CodeHero performance settings$/d' "$MYSQL_CONF" 2>/dev/null || true
# Add settings if not present
if ! grep -q "wait_timeout" "$MYSQL_CONF"; then
echo "" >> "$MYSQL_CONF"
echo "# CodeHero performance settings" >> "$MYSQL_CONF"
echo "wait_timeout=300" >> "$MYSQL_CONF"
echo "interactive_timeout=600" >> "$MYSQL_CONF"
echo " Added MySQL timeout settings (wait=300s, interactive=600s)"
fi
fi
# Create MySQL dev optimization config (prioritizes speed over durability)
MYSQL_DEV_CONF="/etc/mysql/mysql.conf.d/codehero-dev.cnf"
if [ ! -f "$MYSQL_DEV_CONF" ]; then
log_info "Creating MySQL dev optimization config..."
cat > "$MYSQL_DEV_CONF" << 'MYSQLDEVEOF'
[mysqld]
# === CODEHERO DEV OPTIMIZATION ===
# Optimized for development - prioritizes speed over durability
# Reduce disk I/O - flush every 1 second instead of every transaction
innodb_flush_log_at_trx_commit = 2
sync_binlog = 0
# Disable performance schema (saves ~400MB RAM)
performance_schema = OFF
# Disable binary logging (no replication in dev)
skip-log-bin
# Optimize InnoDB for SSD
innodb_io_capacity = 1000
innodb_io_capacity_max = 2000
innodb_flush_method = O_DIRECT
# Increase temp table size for complex queries
tmp_table_size = 64M
max_heap_table_size = 64M
MYSQLDEVEOF
# Restart MySQL to apply new settings
systemctl restart mysql 2>/dev/null || true
log_success "MySQL dev optimization config created (restart required)"
else
echo " MySQL dev optimization config already exists"
fi
# =====================================================
# STEP 6: UPDATE CONFIG (add new parameters if missing)
# =====================================================
log_info "Checking config parameters..."
CONFIG_UPDATED=false
# Add RATE_LIMIT_COOLDOWN_MINUTES if missing
if ! grep -q "^RATE_LIMIT_COOLDOWN_MINUTES" ${CONFIG_DIR}/system.conf 2>/dev/null; then
echo "" >> ${CONFIG_DIR}/system.conf
echo "# Retry Cooldown Settings (added in v2.76.0)" >> ${CONFIG_DIR}/system.conf
echo "RATE_LIMIT_COOLDOWN_MINUTES=30" >> ${CONFIG_DIR}/system.conf
echo " Added: RATE_LIMIT_COOLDOWN_MINUTES=30"
CONFIG_UPDATED=true
fi
# Add RETRY_COOLDOWN_MINUTES if missing
if ! grep -q "^RETRY_COOLDOWN_MINUTES" ${CONFIG_DIR}/system.conf 2>/dev/null; then
if [ "$CONFIG_UPDATED" = false ]; then
echo "" >> ${CONFIG_DIR}/system.conf
echo "# Retry Cooldown Settings (added in v2.76.0)" >> ${CONFIG_DIR}/system.conf
fi
echo "RETRY_COOLDOWN_MINUTES=5" >> ${CONFIG_DIR}/system.conf
echo " Added: RETRY_COOLDOWN_MINUTES=5"
CONFIG_UPDATED=true
fi
# Add MAX_PARALLEL_PROJECTS if missing (added in v2.82.0)
if ! grep -q "^MAX_PARALLEL_PROJECTS" ${CONFIG_DIR}/system.conf 2>/dev/null; then
echo "" >> ${CONFIG_DIR}/system.conf
echo "# Parallel Execution Settings (added in v2.82.0)" >> ${CONFIG_DIR}/system.conf
echo "MAX_PARALLEL_PROJECTS=10" >> ${CONFIG_DIR}/system.conf
echo " Added: MAX_PARALLEL_PROJECTS=10"
CONFIG_UPDATED=true
fi
# Add MAX_PARALLEL_TICKETS if missing
if ! grep -q "^MAX_PARALLEL_TICKETS" ${CONFIG_DIR}/system.conf 2>/dev/null; then
if ! grep -q "Parallel Execution Settings" ${CONFIG_DIR}/system.conf 2>/dev/null; then
echo "" >> ${CONFIG_DIR}/system.conf
echo "# Parallel Execution Settings (added in v2.82.0)" >> ${CONFIG_DIR}/system.conf
fi
echo "MAX_PARALLEL_TICKETS=5" >> ${CONFIG_DIR}/system.conf
echo " Added: MAX_PARALLEL_TICKETS=5"
CONFIG_UPDATED=true
fi
if [ "$CONFIG_UPDATED" = true ]; then
log_success "Config updated with new parameters"
else
echo " (no new parameters needed)"
fi
# =====================================================
# STEP 7: UPDATE SYSTEMD SERVICES
# =====================================================
log_info "Updating systemd service files..."
# Update daemon service with improved startup handling
cat > /etc/systemd/system/codehero-daemon.service << 'SVCEOF'
[Unit]
Description=CodeHero Daemon
After=network.target mysql.service codehero-web.service
Requires=mysql.service
[Service]
Type=simple
User=claude
Group=claude
WorkingDirectory=/opt/codehero
ExecStartPre=/bin/mkdir -p /var/run/codehero
ExecStartPre=/bin/chown claude:claude /var/run/codehero
ExecStart=/usr/bin/python3 /opt/codehero/scripts/claude-daemon.py
Restart=always
RestartSec=10
StartLimitIntervalSec=300
StartLimitBurst=10
StandardOutput=append:/var/log/codehero/daemon.log
StandardError=append:/var/log/codehero/daemon.log
Environment=PYTHONUNBUFFERED=1
Environment=PATH=/home/claude/.local/bin:/usr/local/bin:/usr/bin:/bin
Environment=HOME=/home/claude
[Install]
WantedBy=multi-user.target
SVCEOF
log_success "Systemd services updated"
# =====================================================
# STEP 7.5: UPDATE NGINX CONFIG (if needed)
# =====================================================
# Update nginx config for session-based auth if not already configured
# Checks for absence of auth_request (handles both old basic auth and no-auth configs)
if ! grep -q "auth_request" /etc/nginx/sites-available/codehero-projects 2>/dev/null; then
log_info "Updating nginx config for session-based auth..."
cat > /etc/nginx/sites-available/codehero-projects << 'NGINXPROJECTS'
# CodeHero Web Projects - Port 9867 (HTTPS)
# Session-based auth with per-project cookies
server {
listen 9867 ssl http2;
listen [::]:9867 ssl http2;
server_name _;
ssl_certificate /etc/codehero/ssl/cert.pem;
ssl_certificate_key /etc/codehero/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
root /var/www/projects;
index index.html index.php;
access_log /var/log/nginx/codehero-projects-access.log;
error_log /var/log/nginx/codehero-projects-error.log;
client_max_body_size 500M;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
# Auth validation endpoint (internal)
location = /auth/validate {
internal;
proxy_pass http://127.0.0.1:5000/auth/validate-project-key;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Cookie $http_cookie;
}
location / {
auth_request /auth/validate;
auth_request_set $auth_cookie $upstream_http_set_cookie;
add_header Set-Cookie $auth_cookie;
error_page 403 = @denied;
try_files $uri $uri/ /index.php?$query_string;
}
location @denied {
default_type text/html;
return 403 '<!DOCTYPE html><html><head><title>Access Denied</title><style>body{font-family:system-ui,sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0a0a0f;color:#fff}div{text-align:center;padding:40px}h1{color:#ef4444;margin-bottom:20px}p{color:#94a3b8}</style></head><body><div><h1>Access Denied</h1><p>Use the secure URL with key from CodeHero dashboard.</p></div></body></html>';
}
location ~ \.php$ {
auth_request /auth/validate;
auth_request_set $auth_cookie $upstream_http_set_cookie;
add_header Set-Cookie $auth_cookie;
fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_read_timeout 300s;
}
location ~ /\.ht {
deny all;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg|eot)$ {
auth_request /auth/validate;
expires 7d;
add_header Cache-Control "public, immutable";
add_header Access-Control-Allow-Origin "*" always;
add_header Cross-Origin-Resource-Policy "cross-origin" always;
add_header Cross-Origin-Embedder-Policy "unsafe-none" always;
}
}
NGINXPROJECTS
# Remove old htpasswd file if exists
rm -f /etc/codehero/projects.htpasswd
log_success "Nginx config updated for session-based auth"
fi
# Add CORS headers if missing (for existing installs that have auth_request but no CORS)
if grep -q "auth_request" /etc/nginx/sites-available/codehero-projects 2>/dev/null && \
! grep -q "Access-Control-Allow-Origin" /etc/nginx/sites-available/codehero-projects 2>/dev/null; then
log_info "Adding CORS headers to nginx config..."
# Use sed to add CORS headers after Cache-Control line in static files location
sed -i '/add_header Cache-Control "public, immutable";/a\ add_header Access-Control-Allow-Origin "*" always;\n add_header Cross-Origin-Resource-Policy "cross-origin" always;\n add_header Cross-Origin-Embedder-Policy "unsafe-none" always;' \
/etc/nginx/sites-available/codehero-projects
log_success "CORS headers added to nginx config"
fi
# =====================================================
# STEP 8: RESTART SERVICES
# =====================================================
log_info "Restarting services..."
systemctl daemon-reload
systemctl restart codehero-daemon
sleep 1
systemctl restart codehero-web
sleep 1
systemctl reload nginx 2>/dev/null || systemctl restart nginx 2>/dev/null || true
sleep 1
log_success "Services restarted"
# =====================================================
# STEP 9: VERIFY
# =====================================================
log_info "Verifying services..."
VERIFY_OK=true
if systemctl is-active --quiet codehero-web; then
echo -e " codehero-web: ${GREEN}running${NC}"
else
echo -e " codehero-web: ${RED}not running${NC}"
VERIFY_OK=false
fi
if systemctl is-active --quiet codehero-daemon; then
echo -e " codehero-daemon: ${GREEN}running${NC}"
else
echo -e " codehero-daemon: ${RED}not running${NC}"
VERIFY_OK=false
fi
if systemctl is-active --quiet nginx; then
echo -e " nginx: ${GREEN}running${NC}"
else
echo -e " nginx: ${RED}not running${NC}"
VERIFY_OK=false
fi
echo ""
if [ "$VERIFY_OK" = true ]; then
log_success "Upgrade completed successfully!"
else
log_warning "Upgrade completed with warnings. Check service status."
fi
# Show changelog for this version
echo ""
echo -e "${CYAN}=== What's New in ${NEW_VERSION} ===${NC}"
if [ -f "${SOURCE_DIR}/CHANGELOG.md" ]; then
sed -n "/^## \[${NEW_VERSION}\]/,/^## \[/p" "${SOURCE_DIR}/CHANGELOG.md" | head -n -1 | tail -n +2
else
echo "See CHANGELOG.md for details"
fi
echo ""
echo -e "${GREEN}Upgrade from ${CURRENT_VERSION} to ${NEW_VERSION} complete!${NC}"
echo ""
echo "Backup saved to: ${BACKUP_DIR}/${BACKUP_NAME}.tar.gz"