Repository navigation
Expand file tree
/
Copy pathCustomTerminalEnhanced.tsx
More file actions
1255 lines (1103 loc) · 48.3 KB
/
Copy pathCustomTerminalEnhanced.tsx
File metadata and controls
1255 lines (1103 loc) · 48.3 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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useRef, useEffect } from 'react';
import axios from 'axios';
import TypingText from './TypingText';
import { TypingSpeed } from '../hooks/useTypingEffect';
import { useTheme } from '../hooks/useTheme';
import * as asciiArt from '../utils/asciiArt';
const CONTACT_EMAIL = 'joshterk@javadevjt.tech';
const CONTACT_LINKEDIN = 'https://www.linkedin.com/in/joshuaterk/';
const CONTACT_INFO = `Contact Information:
Email: ${CONTACT_EMAIL}
LinkedIn: ${CONTACT_LINKEDIN}`;
const BANNER_WIDTH_CH = '╔════════════════════════════════════════════════════════════════════════════════════════════╗'.length;
const ICON_ROW_WIDTH_CH = BANNER_WIDTH_CH - 2;
const HOME_PATH = '/home/visitor';
interface CommandOutput {
command: string;
output: string;
type?: 'success' | 'error' | 'info';
}
interface CustomTerminalEnhancedProps {
onToggleScanLines?: () => void;
scanLinesEnabled?: boolean;
}
interface ResumeApiResponse {
text?: string;
downloadUrl?: string;
error?: string;
}
const CustomTerminalEnhanced: React.FC<CustomTerminalEnhancedProps> = ({
onToggleScanLines,
scanLinesEnabled = true
}) => {
const [currentPath, setCurrentPath] = useState(HOME_PATH);
const [command, setCommand] = useState('');
const [history, setHistory] = useState<CommandOutput[]>([]);
const [commandHistory, setCommandHistory] = useState<string[]>([]);
const [historyIndex, setHistoryIndex] = useState(-1);
const [hostname, setHostname] = useState('javadevjt.tech');
const [clientInfo, setClientInfo] = useState<any>(null);
const [suggestions, setSuggestions] = useState<string[]>([]);
const [suggestionIndex, setSuggestionIndex] = useState(-1);
const [turboMode, setTurboMode] = useState(false);
const [secretsUnlocked, setSecretsUnlocked] = useState<string[]>([]);
const [resumeDownloadUrl, setResumeDownloadUrl] = useState('/api/content/resume/download');
const [resumeTextCache, setResumeTextCache] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const terminalRef = useRef<HTMLDivElement>(null);
const { currentTheme, changeTheme, getTheme, listThemes } = useTheme();
// File system structure - will be loaded dynamically
const [fileSystem, setFileSystem] = useState<any>({
[HOME_PATH]: {
type: 'directory',
contents: {
'portfolio': { type: 'directory', contents: {} },
'blog': { type: 'directory', contents: {} },
'about.txt': { type: 'file' },
'contact.txt': { type: 'file' },
'resume.txt': { type: 'file' }
}
}
});
const unlockSecret = (secret: string) => {
if (!secretsUnlocked.includes(secret)) {
setSecretsUnlocked(prev => [...prev, secret]);
}
};
const resumeCommand = async (argsLine?: string) => {
const normalized = (argsLine || '').trim().toLowerCase();
if (normalized === '--download' || normalized === '-d' || normalized === 'download') {
window.open(resumeDownloadUrl, '_blank', 'noopener,noreferrer');
return 'Opening resume PDF in a new tab...';
}
if (resumeTextCache) {
return resumeTextCache;
}
try {
const response = await axios.get<ResumeApiResponse>('/api/content/resume');
if (response.data?.downloadUrl) {
setResumeDownloadUrl(response.data.downloadUrl);
}
if (response.data?.text) {
setResumeTextCache(response.data.text);
return response.data.text;
}
if (response.data?.error) {
return response.data.error;
}
return 'Resume data not available.';
} catch (error: any) {
console.error('Error fetching resume:', error);
return `Unable to load resume (${error.message || 'unknown error'})`;
}
};
const commands: any = {
help: `Available commands:
NAVIGATION:
cd <dir> - Change directory
ls - List directory contents
ll - Long list directory contents
pwd - Print working directory
tree - Visual directory tree
FILE OPERATIONS:
cat <file> - Display file contents
./<file> - Execute file
grep <text> - Search within files
find <name> - Find files by name
INFORMATION:
whoami - Display user info
uname - System information
date - Current date/time
neofetch - System info with ASCII art
history - Show command history
man <cmd> - Manual for command
COMMUNICATION:
contact - Show contact information
CONTENT:
blog - List all blog posts
blog --search <term> - Search blog posts
portfolio - List portfolio projects
portfolio --filter <tech> - Filter by technology
resume - Display ASCII resume
resume --download - Download PDF resume
CUSTOMIZATION:
theme - List available themes
theme <name> - Change terminal theme
turbo - Toggle instant responses
scanlines - Toggle CRT scan lines effect
FUN STUFF:
banner - Display ASCII art banner
cowsay <msg> - ASCII art message
matrix - Matrix effect
coffee - Take a coffee break
clear - Clear terminal
AUTOMOTIVE:
car - Show dream car
diagnostics - System diagnostics
vtec - You know what this does...
TYPE 'secrets' TO SEE DISCOVERED EASTER EGGS`,
whoami: () => clientInfo ? `${clientInfo.username}@${hostname} (${clientInfo.ipAddress})` : 'visitor@javadevjt.tech',
pwd: () => currentPath,
uname: () => `WebTerminal 1.0.0 (Joshua Terk Portfolio)
Platform: ${navigator.platform}
User Agent: ${navigator.userAgent}`,
date: () => new Date().toString(),
neofetch: async () => {
try {
const serverResponse = await axios.get('/api/server/info');
return asciiArt.neofetch(clientInfo, serverResponse.data);
} catch (error) {
console.error('Error fetching server info:', error);
return asciiArt.neofetch(clientInfo, null);
}
},
cowsay: (message: string) => {
if (!message) return 'Usage: cowsay <message>';
return asciiArt.cowsay(message);
},
car: () => {
unlockSecret('automotive_enthusiast');
return asciiArt.carAscii();
},
diagnostics: () => {
unlockSecret('mechanic');
return asciiArt.diagnosticsAscii();
},
vtec: () => {
unlockSecret('vtec_kicked_in');
return asciiArt.vtecAscii();
},
gm: () => {
unlockSecret('gm_employee');
return `
╔════════════════════════════════════════════════════════════╗
║ GENERAL MOTORS ║
║ Excellence Through Innovation ║
╠════════════════════════════════════════════════════════════╣
║ ║
║ Current Role: Senior Software Engineer ║
║ Function: SRE Team Lead ║
║ Division: In-Vehicle Product Cybersecurity ║
║ ║
║ Working on: ║
║ • In-vehicle cryptographic systems ║
║ • Manufacturing plant security ║
║ • Vehicle authentication protocols ║
║ • High-performance distributed systems ║
║ ║
║ "Building the secure future of automotive technology" ║
║ ║
╚════════════════════════════════════════════════════════════╝
`;
},
konami: () => {
unlockSecret('konami_code');
setTurboMode(true);
return asciiArt.konamiCode();
},
hack: () => {
unlockSecret('hacker');
return asciiArt.hackingAnimation();
},
turbo: () => {
setTurboMode(!turboMode);
return `Turbo Mode ${!turboMode ? 'ENABLED' : 'DISABLED'}! ${!turboMode ? '⚡🏎️💨' : '🐌'}`;
},
theme: (themeName?: string) => {
if (!themeName) {
const themes = listThemes();
return `Available themes:
${themes.map(t => t === currentTheme ? `• ${t} (current)` : ` ${t}`).join('\n ')}
Usage: theme <name>`;
}
if (changeTheme(themeName.toLowerCase())) {
unlockSecret('theme_switcher');
return `Theme changed to: ${themeName}`;
} else {
return `Unknown theme: ${themeName}. Type 'theme' to see available themes.`;
}
},
scanlines: () => {
if (onToggleScanLines) {
onToggleScanLines();
return `Scan lines ${!scanLinesEnabled ? 'ENABLED' : 'DISABLED'}! ${!scanLinesEnabled ? '📺 CRT mode activated' : ''}`;
}
return 'Scan lines toggle not available';
},
blog: async (args?: string) => {
try {
if (!args || args.trim() === '') {
// List all blog posts
const response = await axios.get('/api/content/blog/list');
const blogs = response.data;
if (blogs.length === 0) {
return 'No blog posts found.';
}
let output = '\n╔═══════════════════════════════════════════════════════════════╗\n';
output += '║ BLOG POSTS ║\n';
output += '╠═══════════════════════════════════════════════════════════════╣\n\n';
blogs.forEach((blog: any, index: number) => {
output += `${index + 1}. ${blog.title}\n`;
if (blog.published) {
output += ` Published: ${blog.published}\n`;
}
if (blog.tags && blog.tags.length > 0) {
output += ` Tags: ${blog.tags.join(', ')}\n`;
}
if (blog.excerpt) {
output += ` ${blog.excerpt}\n`;
}
output += ` Read: ./blog/${blog.filename.replace('.md', '')}\n\n`;
});
output += '╚═══════════════════════════════════════════════════════════════╝\n';
output += '\nUsage: blog --search <term> to search posts';
return output;
} else if (args.startsWith('--search ') || args.startsWith('-s ')) {
// Search blog posts
const searchTerm = args.replace(/^(-s|--search)\s+/, '');
const response = await axios.get('/api/content/blog/search', {
params: { term: searchTerm }
});
const blogs = response.data;
if (blogs.length === 0) {
return `No blog posts found matching "${searchTerm}"`;
}
let output = `\nSearch results for "${searchTerm}":\n\n`;
blogs.forEach((blog: any, index: number) => {
output += `${index + 1}. ${blog.title}\n`;
if (blog.excerpt) {
output += ` ${blog.excerpt}\n`;
}
output += ` Read: ./blog/${blog.filename.replace('.md', '')}\n\n`;
});
return output;
} else {
return `Unknown option: ${args}\n\nUsage:\n blog - List all posts\n blog --search <term> - Search posts`;
}
} catch (error) {
return 'Error fetching blog posts';
}
},
portfolio: async (args?: string) => {
try {
if (!args || args.trim() === '') {
// List all portfolio projects
const response = await axios.get('/api/content/portfolio/list');
const projects = response.data;
if (projects.length === 0) {
return 'No portfolio projects found.';
}
let output = '\n╔═══════════════════════════════════════════════════════════════╗\n';
output += '║ PORTFOLIO PROJECTS ║\n';
output += '╠═══════════════════════════════════════════════════════════════╣\n\n';
projects.forEach((project: any, index: number) => {
output += `${index + 1}. ${project.title}\n`;
if (project.company) {
output += ` Company: ${project.company}`;
if (project.year) {
output += ` (${project.year})`;
}
output += '\n';
}
if (project.technologies && project.technologies.length > 0) {
output += ` Tech: ${project.technologies.join(', ')}\n`;
}
if (project.excerpt) {
output += ` ${project.excerpt}\n`;
}
output += ` View: ./portfolio/${project.filename.replace('.md', '')}\n\n`;
});
output += '╚═══════════════════════════════════════════════════════════════╝\n';
output += '\nUsage: portfolio --filter <tech> to filter by technology';
return output;
} else if (args.startsWith('--filter ') || args.startsWith('-f ')) {
// Filter portfolio by technology
const tech = args.replace(/^(-f|--filter)\s+/, '');
const response = await axios.get('/api/content/portfolio/filter', {
params: { tech }
});
const projects = response.data;
if (projects.length === 0) {
return `No projects found using "${tech}"`;
}
let output = `\nProjects using "${tech}":\n\n`;
projects.forEach((project: any, index: number) => {
output += `${index + 1}. ${project.title}\n`;
if (project.technologies && project.technologies.length > 0) {
output += ` Tech: ${project.technologies.join(', ')}\n`;
}
output += ` View: ./portfolio/${project.filename.replace('.md', '')}\n\n`;
});
return output;
} else {
return `Unknown option: ${args}\n\nUsage:\n portfolio - List all projects\n portfolio --filter <tech> - Filter by technology`;
}
} catch (error) {
return 'Error fetching portfolio projects';
}
},
resume: async (args?: string) => resumeCommand(args),
cv: async (args?: string) => resumeCommand(args),
coffee: () => {
unlockSecret('coffee_break');
return asciiArt.coffeeBreak();
},
sudo: (_args: string) => {
unlockSecret('tried_sudo');
return `[sudo] password for ${clientInfo?.username || 'visitor'}:
Nice try! 😄 But this is a portfolio site, not a real terminal.
You don't have sudo access here (and wouldn't want it anyway!)
Pro tip: Try 'secrets' to see what easter eggs you've found!`;
},
secrets: () => {
if (secretsUnlocked.length === 0) {
return `No secrets discovered yet! Keep exploring...
Try some commands you might not expect to work. 😉`;
}
const secretDescriptions: Record<string, string> = {
'konami_code': '🎮 Konami Code Master',
'automotive_enthusiast': '🏎️ Automotive Enthusiast',
'mechanic': '🛠️ Mechanic',
'vtec_kicked_in': '⚡ VTEC Activated',
'gm_employee': '🏭 GM Insider',
'hacker': '💻 Hacker (Nice Try)',
'tried_sudo': '🔒 Sudo Attempt',
'coffee_break': '☕ Coffee Lover',
};
let output = '╔════════════════════════════════════════╗\n';
output += '║ DISCOVERED EASTER EGGS ║\n';
output += '╠════════════════════════════════════════╣\n';
secretsUnlocked.forEach(secret => {
output += `║ ${secretDescriptions[secret] || secret}\n`;
});
output += '╚════════════════════════════════════════╝\n';
output += `\nProgress: ${secretsUnlocked.length}/9 secrets discovered`;
return output;
},
history: () => {
if (commandHistory.length === 0) {
return 'No command history';
}
return commandHistory.map((cmd, i) => ` ${i + 1} ${cmd}`).join('\n');
},
tree: () => {
const buildTree = (path: string, prefix: string = ''): string => {
const parts = path.split('/').filter(p => p);
let dirStructure = fileSystem;
for (let i = 0; i < parts.length; i++) {
if (i === 0 && parts[i] === 'home') continue;
if (i === 1 && parts[i] === 'visitor') {
dirStructure = dirStructure['/home/visitor'];
continue;
}
if (dirStructure && dirStructure.contents && dirStructure.contents[parts[i]]) {
dirStructure = dirStructure.contents[parts[i]];
}
}
if (!dirStructure || !dirStructure.contents) {
return '';
}
const items = Object.keys(dirStructure.contents);
let output = '';
items.forEach((item, index) => {
const isLastItem = index === items.length - 1;
const connector = isLastItem ? '└── ' : '├── ';
const entry = dirStructure.contents[item];
if (entry.type === 'directory') {
output += `${prefix}${connector}${item}/\n`;
} else if (entry.type === 'executable') {
output += `${prefix}${connector}${item}*\n`;
} else {
output += `${prefix}${connector}${item}\n`;
}
});
return output;
};
return `${currentPath}/\n${buildTree(currentPath)}`;
},
man: (commandName: string) => {
if (!commandName) {
return 'Usage: man <command>\nTry: man help';
}
const manPages: Record<string, string> = {
help: 'HELP(1)\n\nNAME\n help - display available commands\n\nSYNOPSIS\n help\n\nDESCRIPTION\n Displays a list of all available terminal commands.',
ls: 'LS(1)\n\nNAME\n ls - list directory contents\n\nSYNOPSIS\n ls\n\nDESCRIPTION\n Lists files and directories in the current directory.',
cd: 'CD(1)\n\nNAME\n cd - change directory\n\nSYNOPSIS\n cd <directory>\n\nDESCRIPTION\n Changes the current directory to the specified path.',
cat: 'CAT(1)\n\nNAME\n cat - concatenate and display file contents\n\nSYNOPSIS\n cat <filename>\n\nDESCRIPTION\n Displays the contents of the specified file.',
cowsay: 'COWSAY(1)\n\nNAME\n cowsay - ASCII art speaking cow\n\nSYNOPSIS\n cowsay <message>\n\nDESCRIPTION\n Generates an ASCII art cow saying your message.',
};
return manPages[commandName.toLowerCase()] || `No manual entry for ${commandName}\nTry 'help' for available commands.`;
},
find: (filename: string) => {
if (!filename) {
return 'Usage: find <filename>';
}
const searchFiles = (dir: any, path: string = '/home/visitor'): string[] => {
const results: string[] = [];
if (!dir || !dir.contents) return results;
Object.keys(dir.contents).forEach(key => {
const entry = dir.contents[key];
if (key.toLowerCase().includes(filename.toLowerCase())) {
results.push(`${path}/${key}`);
}
if (entry.type === 'directory') {
results.push(...searchFiles(entry, `${path}/${key}`));
}
});
return results;
};
const results = searchFiles(fileSystem['/home/visitor']);
return results.length > 0 ? results.join('\n') : `find: '${filename}': No such file or directory`;
},
grep: (searchTerm: string) => {
if (!searchTerm) {
return 'Usage: grep <search term>';
}
const currentDir = getCurrentDirectory();
if (!currentDir || !currentDir.contents) {
return 'grep: cannot access current directory';
}
const results: string[] = [];
Object.keys(currentDir.contents).forEach(key => {
if (key.toLowerCase().includes(searchTerm.toLowerCase())) {
results.push(`${key}: matched`);
}
});
return results.length > 0 ? results.join('\n') : `grep: no matches found for '${searchTerm}'`;
},
cd: (directory: string) => {
const requestedPath = !directory || directory === '~'
? HOME_PATH
: directory.startsWith('~/')
? `${HOME_PATH}/${directory.slice(2)}`
: directory.startsWith('/')
? directory
: `${currentPath}/${directory}`;
const pathParts: string[] = [];
for (const segment of requestedPath.split('/').filter(Boolean)) {
if (segment === '.') continue;
if (segment === '..') {
if (pathParts.length > 2) pathParts.pop();
} else {
pathParts.push(segment);
}
}
const newPath = `/${pathParts.join('/')}`;
if (newPath !== HOME_PATH && !newPath.startsWith(`${HOME_PATH}/`)) {
return `cd: ${directory}: No such directory`;
}
let target = fileSystem[HOME_PATH];
for (const segment of pathParts.slice(2)) {
const entry = target?.contents?.[segment];
if (!entry || entry.type !== 'directory') {
return `cd: ${directory}: No such directory`;
}
target = entry;
}
setCurrentPath(newPath);
return `Changed directory to ${newPath}`;
},
ls: () => {
const currentDir = getCurrentDirectory();
if (!currentDir || !currentDir.contents) {
return 'ls: cannot access current directory';
}
const items = Object.keys(currentDir.contents);
if (items.length === 0) {
return '';
}
return items.map(item => {
const entry = currentDir.contents[item];
if (entry.type === 'directory') {
return `${item}/`;
} else if (entry.type === 'executable') {
return `*${item}`;
} else {
return item;
}
}).join('\n');
},
ll: () => {
const currentDir = getCurrentDirectory();
if (!currentDir || !currentDir.contents) {
return 'ls: cannot access current directory';
}
const items = Object.keys(currentDir.contents);
if (items.length === 0) {
return '';
}
const now = new Date();
const formatDate = (date: Date) => {
return date.toLocaleDateString('en-US', {
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
};
const lines = ['total ' + items.length];
lines.push('drwxr-xr-x 2 visitor visitor 4096 ' + formatDate(now) + ' .');
lines.push('drwxr-xr-x 3 visitor visitor 4096 ' + formatDate(now) + ' ..');
items.forEach(item => {
const entry = currentDir.contents[item];
let permissions = '-rw-r--r--';
let size = '1024';
if (entry.type === 'directory') {
permissions = 'drwxr-xr-x';
size = '4096';
} else if (entry.type === 'executable') {
permissions = '-rwxr-xr-x';
size = '2048';
}
lines.push(`${permissions} 1 visitor visitor ${size.padStart(6)} ${formatDate(now)} ${item}`);
});
return lines.join('\n');
},
cat: (filename: string) => {
const currentDir = getCurrentDirectory();
if (!currentDir || !currentDir.contents) {
return `cat: ${filename}: No such file or directory`;
}
if (filename === 'about.txt') {
return `About Joshua Terk:
I am a passionate backend engineer with expertise in building scalable, high-performance systems.
I am a Senior Software Engineer at General Motors and lead an SRE team responsible for in-vehicle cryptographic applications
vital to the day-to-day operation of our manufacturing plants and vehicles.
Key Expertise:
• Microservices Architecture & Design Patterns
• Performance Tuning & Optimization
• API Design & RESTful Services
• DevOps & Site Reliability Engineering
• System Security & Authentication
• Distributed Systems & Scalability
• Spring Boot & Java Ecosystem
With a strong foundation in computer science and years of experience in backend development,
I specialize in turning complex business requirements into efficient, maintainable code that
powers modern applications.`;
} else if (filename === 'contact.txt') {
return `${CONTACT_INFO}
Let's build something amazing.`;
} else if (filename === 'resume.txt') {
if (resumeTextCache) {
return resumeTextCache;
}
return `Resume content is pulled directly from the official PDF. Type 'resume' to load it or 'resume --download' to grab the file.`;
} else {
return `cat: ${filename}: No such file`;
}
},
banner: () => `
╔════════════════════════════════════════════════════════════════════════════════════════════╗
║ ║
║ ██╗ ██████╗ ███████╗██╗ ██╗██╗ ██╗ █████╗ ████████╗███████╗██████╗ ██╗ ██╗ ║
║ ██║██╔═══██╗██╔════╝██║ ██║██║ ██║██╔══██╗ ╚══██╔══╝██╔════╝██╔══██╗██║ ██╔╝ ║
║ ██║██║ ██║███████╗███████║██║ ██║███████║ ██║ █████╗ ██████╔╝█████╔╝ ║
║ ██ ██║██║ ██║╚════██║██╔══██║██║ ██║██╔══██║ ██║ ██╔══╝ ██╔══██╗██╔═██╗ ║
║ ╚█████╔╝╚██████╔╝███████║██║ ██║╚██████╔╝██║ ██║ ██║ ███████╗██║ ██║██║ ██╗ ║
║ ╚════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ║
║ ║
║ Senior Software Engineer & In-Vehicle Product Cybersecurity SRE Team Lead ║
║ General Motors ║
║ ║
╚════════════════════════════════════════════════════════════════════════════════════════════╝
`,
matrix: () => asciiArt.matrixRain() + '\n\nWake up, Neo...\nType \'clear\' to exit the matrix.',
echo: (args: string) => args,
clear: () => {
setHistory([]);
return '';
},
contact: () => `
╔════════════════════════════════════════════════════════════╗
║ CONTACT DETAILS ║
╠════════════════════════════════════════════════════════════╣
║ Email: joshterk@javadevjt.tech ║
║ LinkedIn: https://www.linkedin.com/in/joshuaterk/ ║
╚════════════════════════════════════════════════════════════╝
`
};
const getCurrentDirectory = () => {
const pathParts = currentPath.split('/').filter(p => p);
if (pathParts[0] !== 'home' || pathParts[1] !== 'visitor') {
return null;
}
let current = fileSystem[HOME_PATH];
for (const segment of pathParts.slice(2)) {
if (current?.contents?.[segment]?.type === 'directory') {
current = current.contents[segment];
} else {
return null;
}
}
return current;
};
const getAutocompleteSuggestions = (input: string): string[] => {
if (!input.trim()) {
return Object.keys(commands).filter(cmd => typeof commands[cmd] !== 'function' || cmd !== 'clear');
}
// Special handling for ./ file execution
if (input.startsWith('./')) {
const partialFilename = input.substring(2);
const currentDir = getCurrentDirectory();
if (currentDir && currentDir.contents) {
const items = Object.keys(currentDir.contents);
return items
.filter(item => item.toLowerCase().startsWith(partialFilename.toLowerCase()))
.map(item => './' + item);
}
return [];
}
const parts = input.split(' ');
const currentCmd = parts[0];
if (parts.length === 1) {
return Object.keys(commands).filter(cmd =>
cmd.startsWith(currentCmd) && (typeof commands[cmd] !== 'function' || cmd !== 'clear')
);
}
const args = parts.slice(1);
const currentArg = args[args.length - 1] || '';
const currentDir = getCurrentDirectory();
if (currentDir && currentDir.contents) {
const items = Object.keys(currentDir.contents);
return items.filter(item => item.startsWith(currentArg));
}
return [];
};
const executeFile = async (filename: string): Promise<string> => {
const currentDir = getCurrentDirectory();
if (!currentDir || !currentDir.contents) {
return `./${filename}: No such file or directory`;
}
const fileKey = Object.keys(currentDir.contents).find(key =>
key.toLowerCase() === filename.toLowerCase()
);
if (!fileKey) {
return `./${filename}: No such file or directory`;
}
const file = currentDir.contents[fileKey];
if (!file || file.type !== 'executable') {
return `./${filename}: Permission denied or not executable`;
}
let contentPath = '';
if (currentPath === '/home/visitor/portfolio') {
contentPath = `portfolio/${file.filename}`;
} else if (currentPath === '/home/visitor/blog') {
contentPath = `blog/${file.filename}`;
} else {
return `./${filename}: Cannot execute from this directory`;
}
try {
const response = await axios.get('/api/content/file', { params: { path: contentPath } });
return response.data.content || 'Content not available';
} catch (error: any) {
console.error('Error loading content:', error);
return `./${filename}: Error loading content - ${error.message}`;
}
};
const executeCommand = async (cmd: string) => {
const trimmedCmd = cmd.trim();
if (!trimmedCmd) return;
// Special handling for file execution (./ prefix)
// Don't split by spaces to support filenames with spaces
if (trimmedCmd.startsWith('./')) {
const filename = trimmedCmd.substring(2);
setCommand('');
executeFile(filename).then((result: string) => {
setHistory(prev => [...prev, { command: trimmedCmd, output: result }]);
setCommandHistory(prev => [...prev, trimmedCmd]);
}).catch((error: any) => {
setHistory(prev => [...prev, { command: trimmedCmd, output: `Error: ${error.message}`, type: 'error' }]);
setCommandHistory(prev => [...prev, trimmedCmd]);
});
return;
}
const [commandName, ...args] = trimmedCmd.split(' ');
const commandKey = commandName.toLowerCase();
let output = '';
let outputType: 'success' | 'error' | 'info' = 'info';
if (commandKey === 'clear') {
commands.clear();
setCommand(''); // Clear the input field
return;
} else if (commands[commandKey as keyof typeof commands]) {
const cmdFunc = commands[commandKey as keyof typeof commands];
if (typeof cmdFunc === 'string') {
output = cmdFunc;
} else if (typeof cmdFunc === 'function') {
try {
if (commandKey === 'echo' || commandKey === 'cowsay' || commandKey === 'man' ||
commandKey === 'find' || commandKey === 'grep' || commandKey === 'sudo' ||
commandKey === 'theme' || commandKey === 'blog' || commandKey === 'portfolio' ||
commandKey === 'resume' || commandKey === 'cv') {
output = await cmdFunc(args.join(' '));
} else if (commandKey === 'cd') {
output = cmdFunc(args.join(' ').trim());
outputType = 'success';
} else if (commandKey === 'cat') {
output = await cmdFunc(args.join(' ').trim());
} else {
output = await cmdFunc();
}
} catch (error: any) {
output = `Error executing ${commandName}: ${error.message}`;
outputType = 'error';
}
}
} else {
output = `Command not found: ${commandName}. Type 'help' for available commands.`;
outputType = 'error';
}
setHistory(prev => [...prev, { command: trimmedCmd, output, type: outputType }]);
setCommandHistory(prev => [...prev, trimmedCmd]);
setCommand('');
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
executeCommand(command);
setSuggestions([]);
setSuggestionIndex(-1);
} else if (e.key === 'Tab') {
e.preventDefault();
const newSuggestions = getAutocompleteSuggestions(command);
if (newSuggestions.length === 1) {
const parts = command.split(' ');
if (parts.length === 1) {
setCommand(newSuggestions[0] + ' ');
} else {
const completedArg = newSuggestions[0];
parts[parts.length - 1] = completedArg;
setCommand(parts.join(' ') + ' ');
}
setSuggestions([]);
setSuggestionIndex(-1);
} else if (newSuggestions.length > 1) {
setSuggestions(newSuggestions);
setSuggestionIndex(0);
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (suggestions.length > 0) {
setSuggestionIndex(Math.max(0, suggestionIndex - 1));
} else if (commandHistory.length > 0) {
const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1);
setHistoryIndex(newIndex);
setCommand(commandHistory[newIndex]);
}
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (suggestions.length > 0) {
setSuggestionIndex(Math.min(suggestions.length - 1, suggestionIndex + 1));
} else if (historyIndex >= 0) {
const newIndex = historyIndex + 1;
if (newIndex >= commandHistory.length) {
setHistoryIndex(-1);
setCommand('');
} else {
setHistoryIndex(newIndex);
setCommand(commandHistory[newIndex]);
}
}
} else {
setSuggestions([]);
setSuggestionIndex(-1);
setHistoryIndex(-1);
}
};
useEffect(() => {
axios.get('/api/client/info')
.then(response => {
setClientInfo(response.data);
setHostname(response.data.hostname || 'javadevjt.tech');
loadDirectoryContents('portfolio');
loadDirectoryContents('blog');
})
.catch(error => {
console.error('Error fetching client info:', error);
setClientInfo({ username: 'visitor', ipAddress: 'unknown', hostname: 'javadevjt.tech' });
});
}, []);
const loadDirectoryContents = (dirName: string) => {
axios.get(`/api/content/directory/${dirName}`)
.then(response => {
const contents = response.data.contents || [];
const executableContents: any = {};
contents.forEach((filename: string) => {
if (filename.endsWith('.md')) {
const nameWithoutExt = filename.replace('.md', '');
executableContents[nameWithoutExt] = {
type: 'executable',
filename: filename,
description: `${dirName} post: ${nameWithoutExt}`
};
}
});
setFileSystem((prev: any) => ({
...prev,
'/home/visitor': {
...prev['/home/visitor'],
contents: {
...prev['/home/visitor'].contents,
[dirName]: {
type: 'directory',
contents: executableContents
}
}
}
}));
})
.catch(error => {
console.error(`Error loading ${dirName} directory:`, error);
});
};
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);