aws-manager 0.30.4

AWS SDK manager
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
use std::io::{self, Error, ErrorKind};

use crate::ec2::{ArchType, OsType};

pub fn start(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("#!/usr/bin/env bash

# print all executed commands to terminal
set -x

# do not mask errors in a pipeline
set -o pipefail

# treat unset variables as an error
set -o nounset

# exit script whenever it errs
set -o errexit

# makes the  default answers be used for all questions
export DEBIAN_FRONTEND=noninteractive

############################################
### Machine Architecture ###################
############################################
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# 'dpkg --print-architecture' to decide amd64/arm64
# 'uname -m' to decide x86_64/aarch64

MACHINE=$(uname -m)
if [ \"$MACHINE\" == \"x86_64\" ]; then
    ARCH=\"amd64\"
elif [ \"$MACHINE\" == \"aarch64\" ]; then
    ARCH=\"arm64\"
else
    echo \"Unknown machine architecture '$MACHINE'\" >&2
    exit 1
fi
echo MACHINE: $MACHINE
echo ARCH: $ARCH

# running as root, in /, check CPU/OS/host info
whoami
pwd
lscpu
cat /etc/os-release
hostnamectl

############################################
### Basic packages #########################
############################################

sudo mkdir -p /etc/systemd/system
sudo chown -R ubuntu:ubuntu /etc/systemd/system

while [ 1 ]; do
    sudo apt-get update -yq
    sudo apt-get upgrade -yq
    sudo apt-get install -yq \\
    build-essential tmux git xclip htop zsh \\
    jq curl wget \\
    zip unzip gzip tar \\
    libssl-dev \\
    pkg-config lsb-release vim \\
    linux-headers-$(uname -r)
    sudo apt-get clean
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
while [ 1 ]; do
    sudo apt update
    sudo apt clean all
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

# /usr/sbin/iptables
which iptables
iptables --version

# /usr/sbin/iptables-save
which iptables-save
iptables-save --version

# /usr/sbin/iptables-restore
which iptables-restore
iptables-restore --version

/usr/bin/gcc --version
/usr/bin/c++ -v

if ! command -v lsb_release &> /dev/null
then
    echo \"lsb_release could not be found\"
    exit 1
fi
lsb_release --all

# sudo sh -c \"$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)\"
# chsh -s /bin/zsh
# sudo chown -R ubuntu /home/ubuntu/.cache
# sudo chown -R ubuntu /home/ubuntu/.zshrc
# sudo chown -R ubuntu /home/ubuntu/.zsh_history

mkdir -p /home/ubuntu/.vim
sudo chown -R ubuntu /home/ubuntu/.vim
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn update_bash_profile(
    os_type: OsType,
    anaconda_installed: bool,
    python_installed: bool,
    rust_installed: bool,
    cuda_toolkit_installed: bool,
    go_installed: bool,
    kubectl_installed: bool,
    helm_installed: bool,
    data_directory_mounted: bool,
) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            let mut paths = Vec::new();
            if anaconda_installed {
                paths.push("/home/ubuntu/anaconda3/bin".to_string());
            }
            if python_installed {
                paths.push("/home/ubuntu/.local/bin".to_string());
            }
            if rust_installed {
                paths.push("/home/ubuntu/.cargo/bin".to_string());
            }
            if cuda_toolkit_installed {
                paths.push("/usr/local/cuda-12.2/bin".to_string());
            }

            let mut profile = String::from(
                // https://stackoverflow.com/questions/27920806/how-to-avoid-heredoc-expanding-variables
                "cat << 'EOF' >> /home/ubuntu/.profile
HISTSIZE=1000000
HISTFILESIZE=2000000

alias ..='cd ..'
alias hh='history | grep'
alias t=tmux
alias kill-tmux='tmux list-sessions; tmux kill-session -a;'
alias kill-docker='docker kill $(docker ps -q)'
alias clean-docker='docker system prune --all --force; docker rmi $(docker images -a -q);'
alias pbcopy='xclip -selection clipboard'
alias gith='git rev-parse HEAD; git rev-parse HEAD | pbcopy'

export VISUAL=vim
export EDITOR=vim
export GPG_TTY=$(tty)

",
            );
            let mut bashrc = String::from(
                // https://stackoverflow.com/questions/27920806/how-to-avoid-heredoc-expanding-variables
                "cat << 'EOF' >> /home/ubuntu/.bashrc
HISTSIZE=1000000
HISTFILESIZE=2000000

alias ..='cd ..'
alias hh='history | grep'
alias t=tmux
alias kill-tmux='tmux list-sessions; tmux kill-session -a;'
alias kill-docker='docker kill $(docker ps -q)'
alias clean-docker='docker system prune --all --force; docker rmi $(docker images -a -q);'
alias pbcopy='xclip -selection clipboard'
alias gith='git rev-parse HEAD; git rev-parse HEAD | pbcopy'

export VISUAL=vim
export EDITOR=vim
export GPG_TTY=$(tty)

",
            );

            if go_installed {
                paths.push("/usr/local/go/bin".to_string());
                paths.push("/home/ubuntu/go/bin".to_string());

                profile.push_str(
                    "export GOPATH=/home/ubuntu/go
",
                );
                bashrc.push_str(
                    "export GOPATH=/home/ubuntu/go
",
                );
            }

            if kubectl_installed {
                profile.push_str(
                    "alias k=kubectl
",
                );
                bashrc.push_str(
                    "alias k=kubectl
",
                );
            }
            if helm_installed {
                profile.push_str(
                    "alias h=helm
",
                );
                bashrc.push_str(
                    "alias h=helm
",
                );
            }

            let path_line = format!(
                "export PATH={}:$PATH
",
                paths.join(":")
            );

            profile.push_str(&path_line);
            if rust_installed {
                // only include in the profile
                profile.push_str(
                    ". /opt/rust/env
",
                )
            }
            bashrc.push_str(&path_line);
            if rust_installed {
                // only include in the bashrc
                bashrc.push_str(
                    ". /opt/rust/env
",
                )
            }

            // add "path_line" once more to use the PATH
            // during the following executions
            if data_directory_mounted {
                Ok(format!(
                    "
###########################
# setting up user bash profiles

{profile}
# set permissions
sudo chown -R $(whoami) /data
sudo chown -R ubuntu /data
EOF

{bashrc}
# set permissions
sudo chown -R $(whoami) /data
sudo chown -R ubuntu /data
EOF

{path_line}"
                ))
            } else {
                Ok(format!(
                    "
###########################
# setting up user bash profiles

{profile}
EOF

{bashrc}
EOF

{path_line}"
                ))
            }
        }
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn imds(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => Ok("
###########################
# install imds utils
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# https://github.com/awslabs/amazon-eks-ami/tree/master/files/bin

while [ 1 ]; do
    rm -f /tmp/imds || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/bin/imds\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/imds
sudo mv /tmp/imds /usr/bin/imds
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn provider_id(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => Ok("
###########################
# install provider-id utils
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# https://github.com/awslabs/amazon-eks-ami/tree/master/files/bin

while [ 1 ]; do
    rm -f /tmp/provider-id || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/bin/provider-id\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/provider-id
sudo mv /tmp/provider-id /usr/bin/provider-id
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn vercmp(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => Ok("
###########################
# install vercmp utils
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# https://github.com/awslabs/amazon-eks-ami/tree/master/files/bin

while [ 1 ]; do
    rm -f /tmp/vercmp || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/bin/vercmp\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/vercmp
sudo mv /tmp/vercmp /usr/bin/vercmp
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn setup_local_disks(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => Ok("
###########################
# install setup-local-disks utils
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# https://github.com/awslabs/amazon-eks-ami/tree/master/files/bin

while [ 1 ]; do
    rm -f /tmp/setup-local-disks || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/bin/setup-local-disks\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/setup-local-disks
sudo mv /tmp/setup-local-disks /usr/bin/setup-local-disks
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn mount_bpf_fs(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => Ok("
###########################
# install mount-bpf-fs utils
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# https://github.com/awslabs/amazon-eks-ami/tree/master/files/bin

while [ 1 ]; do
    rm -f /tmp/mount-bpf-fs || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/bin/mount-bpf-fs\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/mount-bpf-fs
sudo mv /tmp/mount-bpf-fs /usr/bin/mount-bpf-fs
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn time_sync(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install time sync utils

# https://github.com/awslabs/amazon-eks-ami/tree/master/files/bin/configure-clocksource
while [ 1 ]; do
    rm -f /tmp/configure-clocksource || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/bin/configure-clocksource\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
chmod +x /tmp/configure-clocksource
sudo mv /tmp/configure-clocksource /usr/bin/configure-clocksource

# https://github.com/awslabs/amazon-eks-ami/commit/056e31f8c7477e893424abce468cb32bbcd1f079#diff-049390d14bc3ea2d7882ff0f108e2802ad9b043336c5fa637e93581d9a7fdfc2
while [ 1 ]; do
    rm -f /tmp/configure-clocksource.service || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/configure-clocksource.service\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo mv /tmp/configure-clocksource.service /etc/systemd/system/configure-clocksource.service
sudo chown root:root /etc/systemd/system/configure-clocksource.service
systemctl daemon-reload
systemctl enable --now configure-clocksource
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn system_limit_bump(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => Ok("
###########################
# bumping up system limits
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
echo fs.inotify.max_user_instances=8192 | sudo tee -a /etc/sysctl.conf
echo vm.max_map_count=524288 | sudo tee -a /etc/sysctl.conf

# e.g.,
# \"Accept error: accept tcp [::]:9650: accept4: too many open files; retrying in 1s\"
sudo echo \"* hard nofile 1000000\" >> /etc/security/limits.conf
sudo echo \"* soft nofile 1000000\" >> /etc/security/limits.conf
sudo sysctl -w fs.file-max=1000000
sudo sysctl -p
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn aws_cli(arch_type: ArchType, os_type: OsType) -> io::Result<String> {
    match (arch_type, os_type) {
        (ArchType::Amd64
            | ArchType::Amd64GpuP4NvidiaTeslaA100
            | ArchType::Amd64GpuG3NvidiaTeslaM60
            | ArchType::Amd64GpuG4adRadeon
            | ArchType::Amd64GpuG5NvidiaA10G, OsType::Ubuntu2004 | OsType::Ubuntu2204) => Ok(
            "
###########################
# install AWS CLI
# https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html

# 'uname -m' to decide x86_64/aarch64
while [ 1 ]; do
    sudo rm -f /tmp/awscli-exe-linux-$(uname -m).zip || true;
    sudo apt-get update -yq && sudo apt-get install -yq wget unzip && wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

# 'uname -m' to decide x86_64/aarch64
unzip /tmp/awscli-exe-linux-$(uname -m).zip && sudo ./aws/install
/usr/local/bin/aws --version

# /usr/local/bin/aws
which aws

# AWS CLI SSM session manager
# https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-debian.html
# 'uname -m' to decide x86_64/aarch64
curl https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb -o /tmp/session-manager-plugin.deb
sudo dpkg -i /tmp/session-manager-plugin.deb
rm -f /tmp/session-manager-plugin.deb
".to_string()),

    (ArchType::Arm64, OsType::Ubuntu2004 | OsType::Ubuntu2204) => Ok(
    "
###########################
# install AWS CLI
# https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html

# 'uname -m' to decide x86_64/aarch64
while [ 1 ]; do
sudo rm -f /tmp/awscli-exe-linux-$(uname -m).zip || true;
sudo apt-get update -yq && sudo apt-get install -yq wget unzip && wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip
if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
sleep 2s;
done;

# 'uname -m' to decide x86_64/aarch64
unzip /tmp/awscli-exe-linux-$(uname -m).zip && sudo ./aws/install
/usr/local/bin/aws --version

# /usr/local/bin/aws
which aws

# AWS CLI SSM session manager
# https://docs.aws.amazon.com/systems-manager/latest/userguide/install-plugin-debian.html
# 'uname -m' to decide x86_64/aarch64
curl https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_arm64/session-manager-plugin.deb -o /tmp/session-manager-plugin.deb
sudo dpkg -i /tmp/session-manager-plugin.deb
rm -f /tmp/session-manager-plugin.deb
".to_string()),

        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            "os_type not supported",
        )),
    }
}

pub fn ssm_agent(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(
            "
###########################
# install ssm agent
# https://docs.aws.amazon.com/systems-manager/latest/userguide/agent-install-ubuntu.html

sudo snap install amazon-ssm-agent --classic
sudo systemctl enable snap.amazon-ssm-agent.amazon-ssm-agent.service
sudo systemctl restart snap.amazon-ssm-agent.amazon-ssm-agent.service
mkdir -p /etc/systemd/system/snap.amazon-ssm-agent.amazon-ssm-agent.service.d
cat > /tmp/amazon-ssm-agent-10-restart-always.conf << EOF
[Service]
Restart=always
RestartSec=60s
EOF

sudo mkdir -p /etc/systemd/system/snap.amazon-ssm-agent.amazon-ssm-agent.service.d
sudo mv /tmp/amazon-ssm-agent-10-restart-always.conf /etc/systemd/system/snap.amazon-ssm-agent.amazon-ssm-agent.service.d/10-restart-always.conf
sudo systemctl start --no-block snap.amazon-ssm-agent.amazon-ssm-agent.service
".to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn cloudwatch_agent(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(format!(
            "
###########################
# install cloudwatch agent
# https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/QuickStartEC2Instance.html
# 'dpkg --print-architecture' to decide amd64/arm64

while [ 1 ]; do
    rm -f /tmp/amazon-cloudwatch-agent.deb || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/$(dpkg --print-architecture)/latest/amazon-cloudwatch-agent.deb\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
while [ 1 ]; do
    sudo dpkg -i -E /tmp/amazon-cloudwatch-agent.deb
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
"
        )),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn static_volume_provisioner(
    os_type: OsType,
    id: &str,
    region: &str,
    volume_type: &str,
    volume_size: u32,
    volume_iops: u32,
    volume_throughput: u32,
    ebs_device_name: &str,
    provisioner_initial_wait_random_seconds: usize,
) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(format!(
            "
###########################
# install aws-volume-manager for x86_64 (mac, linux x86), arm64 (M*), aarch64 (graviton)
# https://github.com/ava-labs/volume-manager/releases

# 'uname -m' to decide x86_64/aarch64
while [ 1 ]; do
    rm -f /tmp/aws-volume-provisioner.$(uname -m)-{os_type}-linux-gnu || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://github.com/ava-labs/volume-manager/releases/download/latest/aws-volume-provisioner.$(uname -m)-{os_type}-linux-gnu\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/aws-volume-provisioner.$(uname -m)-{os_type}-linux-gnu
/tmp/aws-volume-provisioner.$(uname -m)-{os_type}-linux-gnu --version

/tmp/aws-volume-provisioner.$(uname -m)-{os_type}-linux-gnu \\
--log-level=info \\
--region {region} \\
--initial-wait-random-seconds={provisioner_initial_wait_random_seconds} \\
--id-tag-key=Id \\
--id-tag-value={id} \\
--kind-tag-key=Kind \\
--kind-tag-value=aws-volume-provisioner \\
--ec2-tag-asg-name-key=ASG_NAME \\
--asg-tag-key=autoscaling:groupName \\
--volume-type={volume_type} \\
--volume-size={volume_size} \\
--volume-iops={volume_iops} \\
--volume-throughput={volume_throughput} \\
--ebs-device-name={ebs_device_name} \\
--block-device-name=/dev/nvme1n1 \\
--filesystem-name=ext4 \\
--mount-directory-path=/data

# set permissions
sudo chown -R $(whoami) /data
sudo chown -R ubuntu /data
",
            os_type = os_type.as_str(),
            id=id,
            region=region,
            volume_type=volume_type,
            volume_size=volume_size,
            volume_iops=volume_iops,
            volume_throughput=volume_throughput,
            ebs_device_name=ebs_device_name,
            provisioner_initial_wait_random_seconds=provisioner_initial_wait_random_seconds,
        )),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn static_ip_provisioner(
    os_type: OsType,
    id: &str,
    region: &str,
    provisioner_initial_wait_random_seconds: usize,
) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(format!(
            "
###########################
# install aws-ip-manager for x86_64 (mac, linux x86), arm64 (M*), aarch64 (graviton)
# https://github.com/ava-labs/ip-manager/releases

# 'uname -m' to decide x86_64/aarch64
while [ 1 ]; do
    rm -f /tmp/aws-ip-provisioner.$(uname -m)-{os_type}-linux-gnu || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://github.com/ava-labs/ip-manager/releases/download/latest/aws-ip-provisioner.$(uname -m)-{os_type}-linux-gnu\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/aws-ip-provisioner.$(uname -m)-{os_type}-linux-gnu
/tmp/aws-ip-provisioner.$(uname -m)-{os_type}-linux-gnu --version

/tmp/aws-ip-provisioner.$(uname -m)-{os_type}-linux-gnu \\
--log-level=info \\
--region {region} \\
--initial-wait-random-seconds={provisioner_initial_wait_random_seconds} \\
--id-tag-key=Id \\
--id-tag-value={id} \\
--kind-tag-key=Kind \\
--kind-tag-value=aws-ip-provisioner \\
--ec2-tag-asg-name-key=ASG_NAME \\
--asg-tag-key=autoscaling:groupName \\
--mounted-eip-file-path=/data/eip.yaml
",
            os_type = os_type.as_str(),
            id=id,
            region=region,
            provisioner_initial_wait_random_seconds=provisioner_initial_wait_random_seconds,
        )),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn anaconda(os_type: OsType) -> io::Result<String> {
    match os_type {
        // eval "$(/home/ubuntu/anaconda3/bin/conda shell.bash hook)"
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install anaconda
# https://docs.conda.io/projects/conda/en/latest/user-guide/install/linux.html
# https://www.anaconda.com/download#downloads

wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://repo.anaconda.com/archive/Anaconda3-2023.03-1-Linux-$(uname -m).sh\"

# batch mode to not interrupt
# 'uname -m' to decide x86_64/aarch64
export PREFIX=/home/ubuntu/anaconda3
PREFIX=/home/ubuntu/anaconda3 HOME=/home/ubuntu sh /tmp/Anaconda3-2023.03-1-Linux-$(uname -m).sh -b || true
rm -f /tmp/Anaconda3-2023.03-1-Linux-$(uname -m).sh

# conda update conda -y
# /home/ubuntu/anaconda3/bin/conda

sudo chown -R ubuntu /home/ubuntu/anaconda3/pkgs || true
sudo chown -R ubuntu /home/ubuntu/.conda/pkgs || true
sudo chown -R ubuntu /home/ubuntu/anaconda3/envs || true
sudo chown -R ubuntu /home/ubuntu/.conda/envs || true
sudo chown -R ubuntu /home/ubuntu/anaconda3/etc/conda || true
sudo chown -R ubuntu /home/ubuntu/anaconda3 || true

# check versions
which conda
/home/ubuntu/anaconda3/bin/conda --version

# check default system versions
which python3
python3 --version
which python
python --version
which pip3
pip3 --version
which pip
pip --version

# check versions from conda
/home/ubuntu/anaconda3/bin/python3 --version
/home/ubuntu/anaconda3/bin/python --version
/home/ubuntu/anaconda3/bin/pip3 --version
/home/ubuntu/anaconda3/bin/pip --version
".to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn python(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install python

sudo apt-get install -yq python3-pip
sudo apt install -yq python-is-python3

# /usr/bin/python3
which python3
python3 --version

# /usr/bin/python
which python
python --version

pip3 install --upgrade pip

# /usr/local/bin/pip3
which pip3
pip3 --version

# /usr/local/bin/pip
which pip
pip --version
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn rust(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            Ok("
###########################
# install rust
# https://www.rust-lang.org/tools/install

export RUSTUP_HOME=/opt/rust
export CARGO_HOME=/opt/rust
sudo mkdir -p /opt/rust
sudo chown -R ubuntu /opt/rust || true
sudo curl --proto '=https' --tlsv1.2 -sSf --retry 70 --retry-delay 1 https://sh.rustup.rs | bash -s -- -y --no-modify-path --default-toolchain stable --profile default
sudo -H -u ubuntu bash -c 'source /opt/rust/env && rustup default stable'

. /opt/rust/env

# /opt/rust/bin/rustc
which rustc
rustc --version
".to_string())
        }

        OsType::Al2023 => {
            Ok("
###########################
# install rust
# https://www.rust-lang.org/tools/install

export RUSTUP_HOME=/opt/rust
export CARGO_HOME=/opt/rust
curl --proto '=https' --tlsv1.2 -sSf --retry 70 --retry-delay 1 https://sh.rustup.rs | bash -s -- -y --no-modify-path --default-toolchain stable --profile default
sudo -H -u ec2-user bash -c 'source /opt/rust/env && rustup default stable'

. /opt/rust/env

# /opt/rust/bin/rustc
which rustc
rustc --version
".to_string())
        }

        _  => {
            Err(Error::new(
                ErrorKind::InvalidInput,
                format!("os_type '{}' not supported", os_type.as_str()),
            ))
        }
    }
}

pub fn go(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            Ok("
###########################
# install go for amd64 or arm64
# https://go.dev/dl
# 'dpkg --print-architecture' to decide amd64/arm64

# sudo rm -rf /usr/local/go
# sudo curl -s --retry 70 --retry-delay 1 https://storage.googleapis.com/golang/go1.20.7.linux-$(dpkg --print-architecture).tar.gz | sudo tar -C /usr/local/ -xz
wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://go.dev/dl/go1.20.7.linux-$(dpkg --print-architecture).tar.gz\"
rm -rf /usr/local/go && tar -C /usr/local -xzf /tmp/go1.20.7.linux-$(dpkg --print-architecture).tar.gz

/usr/local/go/bin/go version
go version || true
".to_string())
        }
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn docker(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(
            "
###########################
# install docker
# 'dpkg --print-architecture' to decide amd64/arm64
# 'lsb_release -cs' to decide jammy/focal/*

if ! command -v lsb_release &> /dev/null
then
    echo \"lsb_release could not be found\"
    exit 1
fi

while [ 1 ]; do
    sudo apt-get install -yq ca-certificates gnupg
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
while [ 1 ]; do
    sudo rm -f /usr/share/keyrings/docker-archive-keyring.gpg && curl -fsSL --retry 70 --retry-delay 1 https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
echo \"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \\
    $(lsb_release -cs) stable\" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
while [ 1 ]; do
    sudo apt-get update -y && sudo apt-get install -yq docker-ce docker-ce-cli containerd.io docker-compose-plugin
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

sudo systemctl enable docker

sudo usermod -aG docker ubuntu

sudo newgrp docker
sudo systemctl start docker.service
sudo systemctl enable --now docker
sudo docker ps
sudo docker version

# /usr/bin/containerd
which containerd
containerd --version

# /usr/bin/ctr
which ctr
ctr --version || true
ctr version || true

# /usr/bin/docker
which docker
docker ps
docker version
".to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn containerd(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            Ok("
###########################
# install containerd
# https://containerd.io/downloads/
# 'dpkg --print-architecture' to decide amd64/arm64

# /usr/bin/containerd
which containerd || true
containerd --version || true

while [ 1 ]; do
    export CONTAINERD_CURRENT_VERSION=$(curl -Ls --retry 70 --retry-delay 1 https://api.github.com/repos/containerd/containerd/releases/latest | grep 'tag_name' | cut -d'v' -f2 | cut -d'\"' -f1)
    rm -f /tmp/containerd-${CONTAINERD_CURRENT_VERSION}-linux-$(dpkg --print-architecture).tar.gz || true;
    rm -rf /tmp/containerd || true;
    mkdir -p /tmp/containerd
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://github.com/containerd/containerd/releases/download/v${CONTAINERD_CURRENT_VERSION}/containerd-${CONTAINERD_CURRENT_VERSION}-linux-$(dpkg --print-architecture).tar.gz\" -O - | tar -xzv -C /tmp/containerd
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/containerd/bin/*
sudo mv /tmp/containerd/bin/* /usr/bin/
rm -rf /tmp/containerd

# /usr/bin/containerd
which containerd
containerd --version

# /usr/bin/ctr
which ctr
ctr --version || true
ctr version || true
".to_string())
        }
        _  => {
            Err(Error::new(
                ErrorKind::InvalidInput,
                format!("os_type '{}' not supported", os_type.as_str()),
            ))
        }
    }
}

pub fn runc(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install runc
# https://github.com/opencontainers/runc
# 'dpkg --print-architecture' to decide amd64/arm64

which runc || true
runc --version || true

# this removes \"containerd.io docker-ce\"
# sudo apt-get install -yq runc

sudo apt-get install -yq libseccomp-dev

# rm -rf /tmp/runc
# git clone https://github.com/opencontainers/runc /tmp/runc
# cd /tmp/runc
# make
# sudo make install

while [ 1 ]; do
    export RUNC_CURRENT_VERSION=$(curl -Ls --retry 70 --retry-delay 1 https://api.github.com/repos/opencontainers/runc/releases/latest | grep 'tag_name' | cut -d'v' -f2 | cut -d'\"' -f1)
    rm -f /tmp/runc.$(dpkg --print-architecture) || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://github.com/opencontainers/runc/releases/download/v${RUNC_CURRENT_VERSION}/runc.$(dpkg --print-architecture)\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/runc.$(dpkg --print-architecture)
sudo mv /tmp/runc.$(dpkg --print-architecture) /usr/bin/runc

# /usr/bin/runc
which runc
runc --version
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn cni_plugins(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => Ok("
###########################
# install CNI plugins
# https://github.com/containernetworking/plugins
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# 'dpkg --print-architecture' to decide amd64/arm64

while [ 1 ]; do
    export CNI_PLUGIN_CURRENT_VERSION=$(curl -Ls --retry 70 --retry-delay 1 https://api.github.com/repos/containernetworking/plugins/releases/latest | grep 'tag_name' | cut -d'v' -f2 | cut -d'\"' -f1)
    rm -f /tmp/cni-plugins-linux-$(dpkg --print-architecture)-v${CNI_PLUGIN_CURRENT_VERSION}.tgz || true;
    rm -rf /tmp/cni-plugins-linux-$(dpkg --print-architecture)-v${CNI_PLUGIN_CURRENT_VERSION} || true;
    rm -rf /tmp/cni-plugins || true;
    mkdir -p /tmp/cni-plugins
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://github.com/containernetworking/plugins/releases/download/v${CNI_PLUGIN_CURRENT_VERSION}/cni-plugins-linux-$(dpkg --print-architecture)-v${CNI_PLUGIN_CURRENT_VERSION}.tgz\" -O - | tar -xzv -C /tmp/cni-plugins
    rm -f /tmp/cni-plugins-linux-$(dpkg --print-architecture)-v${CNI_PLUGIN_CURRENT_VERSION}.tgz || true;
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

ls -lah /tmp/cni-plugins
chmod +x /tmp/cni-plugins/*

sudo mkdir -p /opt/cni/bin
sudo mv /tmp/cni-plugins/* /opt/cni/bin/
rm -rf /tmp/cni-plugins

sudo find /opt/cni/bin/
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn protobuf_compiler(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install protobuf-compiler

sudo apt-get install -yq protobuf-compiler
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn aws_cfn_helper(os_type: OsType, python_pip_bin_path: &str) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(format!("
###########################
# install aws-cfn-bootstrap and other helpers
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-helper-scripts-reference.html
# https://repost.aws/knowledge-center/install-cloudformation-scripts

# install for root
while [ 1 ]; do
    pip3 install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

# pip3 install --user aws-cfn-bootstrap doesn't work
# pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz
# install for user
while [ 1 ]; do
    sudo -H -u ubuntu bash -c '{python_pip_bin_path}/pip3 install --user https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz'
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

# /home/ubuntu/.local/bin/cfn-hup
which cfn-hup
cfn-hup --help

# sudo /sbin/service cfn-hup restart
# sudo ln -s /home/ubuntu/.local/bin/cfn-hup /etc/init.d/cfn-hup
# update-rc.d cfn-hup defaults
#
# sudo systemctl daemon-reload
# sudo systemctl status cfn-hup
"
        )),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn saml2aws(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            Ok("
###########################
# install saml2aws
# https://api.github.com/repos/Versent/saml2aws/releases/latest
# 'dpkg --print-architecture' to decide amd64/arm64

while [ 1 ]; do
    export SAML2AWS_CURRENT_VERSION=$(curl -Ls --retry 70 --retry-delay 1 https://api.github.com/repos/Versent/saml2aws/releases/latest | grep 'tag_name' | cut -d'v' -f2 | cut -d'\"' -f1)
    rm -f /tmp/saml2aws_${SAML2AWS_CURRENT_VERSION}_linux_$(dpkg --print-architecture).tar.gz || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://github.com/Versent/saml2aws/releases/download/v${SAML2AWS_CURRENT_VERSION}/saml2aws_${SAML2AWS_CURRENT_VERSION}_linux_$(dpkg --print-architecture).tar.gz\" -O - | tar -xzv -C /tmp
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/saml2aws
sudo mv /tmp/saml2aws /usr/bin/saml2aws

saml2aws --version
".to_string())
        }
        _  => {
            Err(Error::new(
                ErrorKind::InvalidInput,
                format!("os_type '{}' not supported", os_type.as_str()),
            ))
        }
    }
}

pub fn aws_iam_authenticator(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => {
            Ok("
###########################
# install aws-iam-authenticator
# https://docs.aws.amazon.com/eks/latest/userguide/install-aws-iam-authenticator.html
# 'dpkg --print-architecture' to decide amd64/arm64

while [ 1 ]; do
    export AWS_IAM_AUTHENTICATOR_CURRENT_VERSION=$(curl -Ls --retry 70 --retry-delay 1 https://api.github.com/repos/kubernetes-sigs/aws-iam-authenticator/releases/latest | grep 'tag_name' | cut -d'v' -f2 | cut -d'\"' -f1)
    rm -f /tmp/aws-iam-authenticator_${AWS_IAM_AUTHENTICATOR_CURRENT_VERSION}_linux_$(dpkg --print-architecture) || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://github.com/kubernetes-sigs/aws-iam-authenticator/releases/download/v${AWS_IAM_AUTHENTICATOR_CURRENT_VERSION}/aws-iam-authenticator_${AWS_IAM_AUTHENTICATOR_CURRENT_VERSION}_linux_$(dpkg --print-architecture)\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/aws-iam-authenticator_${AWS_IAM_AUTHENTICATOR_CURRENT_VERSION}_linux_$(dpkg --print-architecture)
sudo mv /tmp/aws-iam-authenticator_${AWS_IAM_AUTHENTICATOR_CURRENT_VERSION}_linux_$(dpkg --print-architecture) /usr/bin/aws-iam-authenticator

# /usr/bin/aws-iam-authenticator
which aws-iam-authenticator
aws-iam-authenticator version
".to_string())
        }
        _  => {
            Err(Error::new(
                ErrorKind::InvalidInput,
                format!("os_type '{}' not supported", os_type.as_str()),
            ))
        }
    }
}

pub fn ecr_credential_helper(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => Ok("
###########################
# install ECR credential helper
# https://github.com/awslabs/amazon-ecr-credential-helper

which docker-credential-ecr-login || true
docker-credential-ecr-login version || true

while [ 1 ]; do
    export ECR_CREDENTIAL_HELPER_CURRENT_VERSION=$(curl -Ls --retry 70 --retry-delay 1 https://api.github.com/repos/awslabs/amazon-ecr-credential-helper/releases/latest | grep 'tag_name' | cut -d'v' -f2 | cut -d'\"' -f1)
    rm -f /tmp/aws-iam-authenticator_${ECR_CREDENTIAL_HELPER_CURRENT_VERSION}_linux_$(dpkg --print-architecture) || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://amazon-ecr-credential-helper-releases.s3.us-east-2.amazonaws.com/${ECR_CREDENTIAL_HELPER_CURRENT_VERSION}/linux-$(dpkg --print-architecture)/docker-credential-ecr-login\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/docker-credential-ecr-login
sudo mv /tmp/docker-credential-ecr-login /usr/bin/docker-credential-ecr-login

# /usr/bin/docker-credential-ecr-login
which docker-credential-ecr-login
docker-credential-ecr-login version
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn ecr_credential_provider(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install ecr-credential-provider
# https://github.com/kubernetes/cloud-provider-aws/tree/master/cmd/ecr-credential-provider
# https://github.com/kubernetes/cloud-provider-aws/releases
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh

if ! command -v go &> /dev/null
then
    echo \"go could not be found\"
    exit 1
fi

while [ 1 ]; do
    HOME=/home/ubuntu GOPATH=/home/ubuntu/go /usr/local/go/bin/go install -v k8s.io/cloud-provider-aws/cmd/ecr-credential-provider@v1.27.1
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

which ecr-credential-provider
chmod +x /home/ubuntu/go/bin/ecr-credential-provider
sudo cp -v /home/ubuntu/go/bin/ecr-credential-provider /usr/bin/ecr-credential-provider

# /usr/bin/ecr-credential-provider
which ecr-credential-provider

# TODO: this blocks
# ecr-credential-provider --help

sudo mkdir -p /etc/eks
sudo mkdir -p /etc/eks/image-credential-provider

sudo cp -v /home/ubuntu/go/bin/ecr-credential-provider /etc/eks/image-credential-provider/ecr-credential-provider

while [ 1 ]; do
    rm -f /tmp/ecr-credential-provider-config.json || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/ecr-credential-provider-config.json\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/ecr-credential-provider-config.json
sudo mv /tmp/ecr-credential-provider-config.json /etc/eks/image-credential-provider/config.json

sudo chown -R root:root /etc/eks
sudo chown -R ubuntu:ubuntu /etc/eks
find /etc/eks
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn kubelet(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 | OsType::Al2023 => {
            Ok("
###########################
# install kubelet
# https://kubernetes.io/releases/
# https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/
# 'dpkg --print-architecture' to decide amd64/arm64

while [ 1 ]; do
    export K8S_CURRENT_VERSION=$(curl -L -s --retry 70 --retry-delay 1 https://dl.k8s.io/release/stable.txt)
    # overwrite with 1.26
    export K8S_CURRENT_VERSION=\"v1.26.7\"

    rm -f /tmp/kubelet || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://dl.k8s.io/release/${K8S_CURRENT_VERSION}/bin/linux/$(dpkg --print-architecture)/kubelet\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/kubelet
sudo mv /tmp/kubelet /usr/bin/kubelet
rm -f /tmp/kubelet

# /usr/bin/kubelet
which kubelet
kubelet --version
".to_string())
        }
        _  => {
            Err(Error::new(
                ErrorKind::InvalidInput,
                format!("os_type '{}' not supported", os_type.as_str()),
            ))
        }
    }
}

pub fn kubectl(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            Ok("
###########################
# install kubectl
# https://kubernetes.io/releases/
# https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/
# 'dpkg --print-architecture' to decide amd64/arm64

while [ 1 ]; do
    export K8S_CURRENT_VERSION=$(curl -L -s --retry 70 --retry-delay 1 https://dl.k8s.io/release/stable.txt)
    # overwrite with 1.26
    export K8S_CURRENT_VERSION=\"v1.26.7\"

    rm -f /tmp/kubectl || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://dl.k8s.io/release/${K8S_CURRENT_VERSION}/bin/linux/$(dpkg --print-architecture)/kubectl\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/kubectl
sudo mv /tmp/kubectl /usr/bin/kubectl
rm -f /tmp/kubectl

# /usr/bin/kubectl
which kubectl
kubectl version --client=true
".to_string())
        }
        _  => {
            Err(Error::new(
                ErrorKind::InvalidInput,
                format!("os_type '{}' not supported", os_type.as_str()),
            ))
        }
    }
}

pub fn helm(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            Ok("
###########################
# install helm
# https://helm.sh/docs/intro/install/
# 'dpkg --print-architecture' to decide amd64/arm64

while [ 1 ]; do
    export HELM_CURRENT_VERSION=$(curl -Ls --retry 70 --retry-delay 1 https://api.github.com/repos/helm/helm/releases/latest | grep 'tag_name' | cut -d'v' -f2 | cut -d'\"' -f1)
    rm -f /tmp/helm-${HELM_CURRENT_VERSION}-linux-$(dpkg --print-architecture).tar.gz || true;
    rm -rf /tmp/helm || true;
    mkdir -p /tmp/helm
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://get.helm.sh/helm-v${HELM_CURRENT_VERSION}-linux-$(dpkg --print-architecture).tar.gz\" -O - | tar -xzv -C /tmp/helm
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

chmod +x /tmp/helm/linux-$(dpkg --print-architecture)/helm
sudo mv /tmp/helm/linux-$(dpkg --print-architecture)/helm /usr/bin/helm
rm -rf /tmp/helm

# /usr/bin/helm
which helm
helm version
".to_string())
        }
        _  => {
            Err(Error::new(
                ErrorKind::InvalidInput,
                format!("os_type '{}' not supported", os_type.as_str()),
            ))
        }
    }
}

pub fn terraform(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            Ok("
###########################
# install terraform
# https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli
# 'dpkg --print-architecture' to decide amd64/arm64
# 'lsb_release -cs' to decide jammy/focal/*

if ! command -v lsb_release &> /dev/null
then
    echo \"lsb_release could not be found\"
    exit 1
fi

while [ 1 ]; do
    sudo apt-get install -yq gnupg software-properties-common
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
while [ 1 ]; do
    sudo rm -f /usr/share/keyrings/hashicorp-archive-keyring.gpg && curl -fsSL --retry 70 --retry-delay 1 https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo gpg --no-default-keyring --keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg --fingerprint

echo \"deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main\" | sudo tee /etc/apt/sources.list.d/hashicorp.list > /dev/null
while [ 1 ]; do
    sudo apt-get update -y && sudo apt-get install -yq terraform
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

# /usr/bin/terraform
which terraform
terraform --version
".to_string())
        }
        _  => {
            Err(Error::new(
                ErrorKind::InvalidInput,
                format!("os_type '{}' not supported", os_type.as_str()),
            ))
        }
    }
}

pub fn ssh_key_with_email(os_type: OsType, email: &str) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(format!(
            "
###########################
# create an SSH key

# NOTE/SECURITY: this must be deleted when building AMI
ssh-keygen -q -t rsa -b 4096 -C \"{email}\" -N '' -f /home/ubuntu/.ssh/id_rsa <<<y >/dev/null 2>&1
eval \"$(ssh-agent -s)\"
ssh-add /home/ubuntu/.ssh/id_rsa
cat /home/ubuntu/.ssh/id_rsa.pub

# set permissions
sudo chown -R $(whoami) /home/ubuntu/.ssh
sudo chown -R ubuntu /home/ubuntu/.ssh
",
            email = email,
        )),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

/// ref. <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking-ena.html#ena-requirements>
/// ref. <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking-ena.html>
/// ref. <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking-ena.html#enhanced-networking-ena-ubuntu>
pub fn ena(os_type: OsType) -> io::Result<String> {
    match  &os_type {
        OsType::Ubuntu2004 |  OsType::Ubuntu2204 => Ok("
###########################
# enable enhanced networking
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking-ena.html#enhanced-networking-ena-ubuntu

while [ 1 ]; do
    sudo apt-get update && sudo apt-get upgrade -y linux-aws
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

if ! command -v imds &> /dev/null
then
    echo \"imds could not be found\"
    exit 1
fi

if ! command -v aws &> /dev/null
then
    echo \"aws could not be found\"
    exit 1
fi

ip link show

# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking-ena.html#test-enhanced-networking-ena
# TODO: this may not work... need pre-installed AMI or restart
modinfo ena || true

# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
INSTANCE_ID=$(imds /latest/meta-data/instance-id)
REGION=$(imds /latest/dynamic/instance-identity/document | jq .region -r)

# must stop the instance first
# aws ec2 stop-instances --region ${REGION} --instance-ids ${INSTANCE_ID}
#
# run this outside of EC2
# An error occurred (IncorrectInstanceState) when calling the ModifyInstanceAttribute operation: The instance 'i-05f974ac421d49bc2' is not in the 'stopped' state.
aws ec2 modify-instance-attribute --region ${REGION} --instance-id ${INSTANCE_ID} --ena-support || true

# expects [ true ]
aws ec2 describe-instances --region ${REGION} --instance-ids ${INSTANCE_ID} --query \"Reservations[].Instances[].EnaSupport\"

# https://docs.aws.amazon.com/cli/latest/reference/ec2/register-image.html
# aws ec2 create-image --region ${REGION} --instance-id ${INSTANCE_ID} --name random-ami-name
# aws ec2 register-image --region ${REGION} --ena-support --name random-ami-name

# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking-ena.html#test-enhanced-networking-ena
# TODO: this may not work... need pre-installed AMI or restart
ip link show
ethtool -i ens5 || true
modinfo ena
"
        .to_string()),

        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported",  os_type.as_str()),
        )),
    }
}

pub fn nvidia_driver(arch_type: ArchType, os_type: OsType) -> io::Result<String> {
    match (&arch_type, &os_type) {
        (ArchType::Amd64GpuG3NvidiaTeslaM60 | ArchType::Amd64GpuG4dnNvidiaT4 | ArchType::Amd64GpuG5NvidiaA10G , OsType::Ubuntu2004) => Ok("
###########################
# install nvidia driver for ubuntu 20.04
# https://www.nvidia.com/Download/index.aspx?lang=en-us
# https://docs.nvidia.com/datacenter/tesla/tesla-installation-notes/index.html
# https://www.nvidia.com/en-us/drivers/unix/

# Release Date:	2021.10.26
DRIVER_VERSION=460.106.00
BASE_URL=https://us.download.nvidia.com/tesla

while [ 1 ]; do
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"${BASE_URL}/${DRIVER_VERSION}/NVIDIA-Linux-$(uname -m)-${DRIVER_VERSION}.run\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

# 'uname -m' to decide x86_64/aarch64
sudo sh /tmp/NVIDIA-Linux-$(uname -m)-${DRIVER_VERSION}.run --silent --ui=none --no-questions
rm -f /tmp/NVIDIA-Linux-$(uname -m)-${DRIVER_VERSION}.run
sudo tail /var/log/nvidia-installer.log

# check the driver
find /usr/lib/modules -name nvidia.ko
find /usr/lib/modules -name nvidia.ko -exec modinfo {} \\;

if ! command -v nvidia-smi &> /dev/null
then
    echo \"nvidia-smi could not be found\"
    exit 1
fi

# /usr/bin/nvidia-smi
which nvidia-smi
nvidia-smi
"
        .to_string()),

        (ArchType::Amd64GpuG3NvidiaTeslaM60 | ArchType::Amd64GpuG4dnNvidiaT4 | ArchType::Amd64GpuG5NvidiaA10G , OsType::Ubuntu2204) => Ok("
###########################
# install nvidia driver for ubuntu 22.04
# https://www.nvidia.com/Download/index.aspx?lang=en-us
# https://docs.nvidia.com/datacenter/tesla/tesla-installation-notes/index.html
# https://www.nvidia.com/en-us/drivers/unix/

# THIS IS DIFFERENT FOR UBUNTU LAPTOP
# e.g.,
# Release Date: 2023.8.29
# DRIVER_VERSION=535.104.05
# https://us.download.nvidia.com/XFree86/Linux-x86_64/535.104.05/NVIDIA-Linux-x86_64-535.104.05.run
#
# in case of rollback
# original system76 ubuntu 22.04 ships
# DRIVER_VERSION=525.105.17
# CUDA_VERSION=12.0

# Release Date: 2023.8.29
DRIVER_VERSION=535.104.05
BASE_URL=https://us.download.nvidia.com/tesla

while [ 1 ]; do
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"${BASE_URL}/${DRIVER_VERSION}/NVIDIA-Linux-$(uname -m)-${DRIVER_VERSION}.run\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

# 'uname -m' to decide x86_64/aarch64
sudo sh /tmp/NVIDIA-Linux-$(uname -m)-${DRIVER_VERSION}.run --silent --ui=none --no-questions
rm -f /tmp/NVIDIA-Linux-$(uname -m)-${DRIVER_VERSION}.run
tail /var/log/nvidia-installer.log

# check the driver
find /usr/lib/modules -name nvidia.ko
find /usr/lib/modules -name nvidia.ko -exec modinfo {} \\;

if ! command -v nvidia-smi &> /dev/null
then
    echo \"nvidia-smi could not be found\"
    exit 1
fi

# /usr/bin/nvidia-smi
which nvidia-smi
nvidia-smi
"
        .to_string()),

        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("arch_type '{}', os_type '{}' not supported", arch_type.as_str(), os_type.as_str()),
        )),
    }
}

pub fn nvidia_cuda_toolkit(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install nvidia cuda toolkit
# this installs cuda 11 by default on ubuntu 20.04
# sudo apt install -yq nvidia-cuda-toolkit
# https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&Distribution=Ubuntu&target_version=20.04&target_type=runfile_local
# https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&Distribution=Ubuntu&target_version=22.04&target_type=runfile_local

# /cuda-installer: error while loading shared libraries: libxml2.so.2: cannot open shared object file: No such file or directory
sudo apt-get install -y libxml2

# this upgrades to CUDA Version: 12.2
CUDA_VERSION=12.2.2
TOOL_KIT_VERSION=535.104.05
BASE_URL=https://developer.download.nvidia.com/compute/cuda

# add --override-driver-check to overwrite
while [ 1 ]; do
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"${BASE_URL}/${CUDA_VERSION}/local_installers/cuda_${CUDA_VERSION}_${TOOL_KIT_VERSION}_linux.run\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

sudo sh /tmp/cuda_${CUDA_VERSION}_${TOOL_KIT_VERSION}_linux.run --silent
rm -f /tmp/cuda_${CUDA_VERSION}_${TOOL_KIT_VERSION}_linux.run
tail /var/log/cuda-installer.log

if ! command -v nvcc &> /dev/null
then
    echo \"nvcc could not be found\"

    # PATH env might not been updated yet
    # exit 1
fi

# /usr/local/cuda-12.2/bin
which nvcc || true
nvcc --version || true
/usr/local/cuda-12.2/bin/nvcc --version

if ! command -v nvidia-smi &> /dev/null
then
    echo \"nvidia-smi could not be found\"
    exit 1
fi

# /usr/bin/nvidia-smi
which nvidia-smi
nvidia-smi
"
            .to_string()),

        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn nvidia_container_toolkit(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install nvidia container toolkit
# https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html

distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -fsSL --retry 70 --retry-delay 1 https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg

curl -s -L --retry 70 --retry-delay 1 https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | \\
sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \\
sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list

sudo apt-get update
sudo apt-get install -yq nvidia-container-toolkit

if ! command -v nvidia-ctk &> /dev/null
then
    echo \"nvidia-ctk could not be found\"
    exit 1
fi

# /usr/bin/nvidia-ctk
which nvidia-ctk
nvidia-ctk --version

if command -v docker &> /dev/null
then
    echo \"checking nvidia container toolkit with docker\"
    # TODO: support other runtime?
    sudo nvidia-ctk runtime configure --runtime=docker

    # https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/getting-started.html#install-nvidia-gpu-operator
    cat /etc/nvidia-container-runtime/config.toml

    # restart docker
    sudo systemctl restart docker

    # test nvidia container toolkit
    sudo docker run --rm --runtime=nvidia --gpus all nvidia/cuda:11.6.2-base-ubuntu20.04 nvidia-smi
else
    echo \"docker not install -- skip checking 'nvidia-ctk runtime configure'\"
fi
"
            .to_string()),

        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn amd_radeon_gpu_driver(arch_type: ArchType, os_type: OsType) -> io::Result<String> {
    match (&arch_type, &os_type) {
        (ArchType::Amd64GpuG4adRadeon, OsType::Ubuntu2004 | OsType::Ubuntu2204) => Ok("
###########################
# install AMD Radeon driver for ubuntu
# https://www.amd.com/en/support/kb/faq/amdgpupro-install
# https://amdgpu-install.readthedocs.io/en/latest/install-prereq.html#downloading-the-installer-package
# https://amdgpu-install.readthedocs.io/en/latest/install-script.html

while [ 1 ]; do
    sudo apt-get -y install linux-modules-extra-aws
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

DRIVER_VERSION1=5.4
DRIVER_VERSION2=5.4.50403-1_all
BASE_URL=https://repo.radeon.com

while [ 1 ]; do
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"${BASE_URL}/${DRIVER_VERSION1}/ubuntu/$(lsb_release -cs)/amdgpu-install_${DRIVER_VERSION2}.deb\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

# 'uname -m' to decide x86_64/aarch64
sudo apt-get -y install /tmp/amdgpu-install_${DRIVER_VERSION2}.deb
sudo sh /tmp/NVIDIA-Linux-$(uname -m)-${DRIVER_VERSION}.run --silent --ui=none --no-questions

if ! command -v amdgpu-install &> /dev/null
then
    echo \"amdgpu-install could not be found\"
    exit 1
fi

# https://amdgpu-install.readthedocs.io/en/latest/install-script.html
sudo amdgpu-install -y --accept-eula --usecase=dkms

# /usr/bin/amdgpu-install
which amdgpu-install
amdgpu-install -h
"
        .to_string()),

        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("arch_type '{}', os_type '{}' not supported", arch_type.as_str(), os_type.as_str()),
        )),
    }
}

pub fn cmake(os_type: OsType, python_pip_bin_path: &str) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(format!("
###########################
# install cmake
# https://askubuntu.com/questions/355565/how-do-i-install-the-latest-version-of-cmake-from-the-command-line

sudo apt purge --auto-remove cmake

# wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor - | sudo tee /etc/apt/trusted.gpg.d/kitware.gpg >/dev/null
# sudo apt-add-repository 'deb https://apt.kitware.com/ubuntu/ focal main'
# sudo apt-add-repository 'deb https://apt.kitware.com/ubuntu/ jammy main'
# sudo apt update -y
# sudo apt install -yq cmake

which pip
{python_pip_bin_path}/pip install --upgrade cmake

which cmake
cmake --version
")),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn dev_bark(
    os_type: OsType,
    python_pip_bin_path: &str,
    data_volume_mounted: bool,
) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            let clone_dir = if data_volume_mounted {
                String::from("/data")
            } else {
                String::from("/home/ubuntu")
            };
            Ok(format!(
                "
###########################
# install bark
# https://github.com/suno-ai/bark

ls -lah {clone_dir}/
git clone https://github.com/suno-ai/bark.git {clone_dir}/bark
cd {clone_dir}/bark

which python
{python_pip_bin_path}/python -m pip install .
which pip
{python_pip_bin_path}/pip install --verbose nltk
"
            ))
        }
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn gcc7(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install gcc7
# gcc downgrade <8, otherwise faiss 'cmake -B build .' fails with
# 138 | #error -- unsupported GNU version! gcc versions later than 8 are not supported!
# https://stackoverflow.com/questions/65605972/cmake-unsupported-gnu-version-gcc-versions-later-than-8-are-not-supported

sudo apt remove -y gcc
sudo apt-get install gcc-7 g++-7 -y
sudo ln -s /usr/bin/gcc-7 /usr/bin/gcc
sudo ln -s /usr/bin/g++-7 /usr/bin/g++
sudo ln -s /usr/bin/gcc-7 /usr/bin/cc
sudo ln -s /usr/bin/g++-7 /usr/bin/c++
/usr/bin/gcc --version
/usr/bin/c++ -v
"
            .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn dev_faiss_gpu(os_type: OsType, data_volume_mounted: bool) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => {
            let clone_dir = if data_volume_mounted {
                String::from("/data")
            } else {
                String::from("/home/ubuntu")
            };
            Ok(format!("
###########################
# install faiss
# https://github.com/facebookresearch/faiss#installing
# https://github.com/facebookresearch/faiss/blob/main/INSTALL.md
# https://github.com/facebookresearch/faiss/wiki/Troubleshooting

# otherwise,
# Could NOT find BLAS (missing: BLAS_LIBRARIES)
sudo apt-get install -yq libopenblas-dev

# otherwise,
# Could NOT find SWIG (missing: SWIG_EXECUTABLE SWIG_DIR python)
sudo apt-get install -yq swig

/usr/bin/gcc --version
/usr/bin/c++ -v

which cmake
cmake --version

ls -lah {clone_dir}/
git clone https://github.com/facebookresearch/faiss.git {clone_dir}/faiss

# generates the system-dependent configuration/build files in the build/ subdirectory
# cd {clone_dir}/faiss
# cmake -B build .

# builds the C++ library
# cd {clone_dir}/faiss
# make -C build -j faiss

# builds the python bindings for Faiss
# cd {clone_dir}/faiss
# make -C build -j swigfaiss

# generates and installs the python package
# cd {clone_dir}/faiss/build/faiss/python
# python setup.py install

# make the compiled library (either libfaiss.a or libfaiss.so on Linux) available system-wide, as well as the C++ headers
# cd {clone_dir}/faiss
# make -C build install
"
        ))
        }
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn eks_worker_node_ami_scratch(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install EKS worker node AMI (from scratch)
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh

#######
# install packages
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
while [ 1 ]; do
    sudo apt-get update -yq
    sudo apt-get upgrade -yq
    sudo apt-get install -yq conntrack socat nfs-kernel-server ipvsadm
    sudo apt-get clean
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;

#######
### Stuff required by \"protectKernelDefaults=true\"
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
cat << EOF | sudo tee -a /etc/sysctl.d/99-amazon.conf
vm.overcommit_memory=1
kernel.panic=10
kernel.panic_on_oops=1
EOF

#######
# set up nvidia-smi check scripts
# https://github.com/awslabs/amazon-eks-ami/blob/master/files/bootstrap.sh
#######
# https://stackoverflow.com/questions/27920806/how-to-avoid-heredoc-expanding-variables
cat << 'EOF' > /tmp/check-nvidia-smi.sh
#!/usr/bin/env bash

if command -v nvidia-smi &> /dev/null; then
    echo \"INFO: nvidia-smi found\"

    nvidia-smi -q > /tmp/nvidia-smi-check
    if [[ \"$?\" == \"0\" ]]; then
        sudo nvidia-smi -pm 1 # set persistence mode
        sudo nvidia-smi --auto-boost-default=0

        GPUNAME=$(nvidia-smi -L | head -n1)
        echo \"INFO: GPU name: $GPUNAME\"

        # set application clock to maximum
        if [[ $GPUNAME == *\"A100\"* ]]; then
            nvidia-smi -ac 1215,1410
        elif [[ $GPUNAME == *\"V100\"* ]]; then
            nvidia-smi -ac 877,1530
        elif [[ $GPUNAME == *\"K80\"* ]]; then
            nvidia-smi -ac 2505,875
        elif [[ $GPUNAME == *\"T4\"* ]]; then
            nvidia-smi -ac 5001,1590
        elif [[ $GPUNAME == *\"M60\"* ]]; then
            nvidia-smi -ac 2505,1177
        else
            echo \"WARN: unsupported GPU\"
        fi
    else
        echo \"ERROR: nvidia-smi check failed!\"
        cat /tmp/nvidia-smi-check
    fi
else
    echo \"INFO: nvidia-smi NOT found\"
fi
EOF
cat /tmp/check-nvidia-smi.sh
chmod +x /tmp/check-nvidia-smi.sh
sudo mv /tmp/check-nvidia-smi.sh /etc/check-nvidia-smi.sh

#######
# set up files
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /etc/eks
sudo chown -R root:root /etc/eks

targets=(
    get-ecr-uri.sh
    eni-max-pods.txt
    bootstrap.sh
    max-pods-calculator.sh
)
for target in \"${targets[@]}\"
do
    while [ 1 ]; do
        rm -f /tmp/${target} || true;
        wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/${target}\"
        if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
        sleep 2s;
    done;
    chmod +x /tmp/${target}
    sudo mv /tmp/${target} /etc/eks/${target}
done

sudo chown -R root:root /etc/eks
sudo chown -R ubuntu:ubuntu /etc/eks
find /etc/eks

#######
# set up iptables
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /etc/eks
sudo chown -R root:root /etc/eks

while [ 1 ]; do
    rm -f /tmp/iptables-restore.service || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/iptables-restore.service\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
chmod +x /tmp/iptables-restore.service
sudo mv /tmp/iptables-restore.service /etc/eks/iptables-restore.service

sudo chown -R root:root /etc/eks
sudo chown -R ubuntu:ubuntu /etc/eks
find /etc/eks

#######
# set up containerd
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /etc/eks
sudo chown -R root:root /etc/eks
sudo mkdir -p /etc/eks/containerd

targets=(
    containerd-config.toml
    kubelet-containerd.service
    sandbox-image.service
    pull-sandbox-image.sh
    pull-image.sh
)
for target in \"${targets[@]}\"
do
    while [ 1 ]; do
        rm -f /tmp/${target} || true;
        wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/${target}\"
        if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
        sleep 2s;
    done;
    chmod +x /tmp/${target}
    sudo mv /tmp/${target} /etc/eks/containerd/${target}
done

sudo chown -R root:root /etc/eks
sudo chown -R ubuntu:ubuntu /etc/eks
find /etc/eks

sudo mkdir -p /etc/systemd/system/containerd.service.d
cat << EOF | sudo tee /etc/systemd/system/containerd.service.d/10-compat-symlink.conf
[Service]
ExecStartPre=/bin/ln -sf /run/containerd/containerd.sock /run/dockershim.sock
EOF

cat << EOF | sudo tee -a /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF

cat << EOF | sudo tee -a /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF

cat << EOF | sudo tee /etc/systemd/system/containerd.service
[Unit]
Description=containerd
Documentation=https://containerd.io

[Service]
Type=notify
ExecStart=/usr/bin/containerd

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl enable containerd
sudo systemctl restart containerd
sudo ctr version || true

#######
# set up log-collector for EKS
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /etc/eks
sudo chown -R root:root /etc/eks
sudo mkdir -p /etc/eks/log-collector-script/

while [ 1 ]; do
    rm -f /tmp/eks-log-collector.sh || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/log-collector-script/linux/eks-log-collector.sh\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
chmod +x /tmp/eks-log-collector.sh
sudo mv /tmp/eks-log-collector.sh /etc/eks/log-collector-script/eks-log-collector.sh

sudo chown -R root:root /etc/eks
sudo chown -R ubuntu:ubuntu /etc/eks
find /etc/eks

#######
# set up logrotate for kube-proxy
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /var/log/journal

while [ 1 ]; do
    rm -f /tmp/logrotate-kube-proxy || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/logrotate-kube-proxy\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo mv /tmp/logrotate-kube-proxy /etc/logrotate.d/kube-proxy
sudo chown root:root /etc/logrotate.d/kube-proxy

while [ 1 ]; do
    rm -f /tmp/logrotate.conf || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/logrotate.conf\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo mv /tmp/logrotate.conf /etc/logrotate.conf
sudo chown root:root /etc/logrotate.conf

#######
# set up kubernetes
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /var/lib/kubernetes
sudo mkdir -p /var/lib/kubelet
sudo mkdir -p /etc/kubernetes
sudo mkdir -p /etc/kubernetes/manifests
sudo mkdir -p /etc/kubernetes/kubelet
sudo mkdir -p /etc/systemd/system/kubelet.service.d

while [ 1 ]; do
    rm -f /tmp/kubelet-kubeconfig || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/kubelet-kubeconfig\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo mv /tmp/kubelet-kubeconfig /var/lib/kubelet/kubeconfig
sudo chown root:root /var/lib/kubelet/kubeconfig

while [ 1 ]; do
    rm -f /tmp/kubelet.service || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/kubelet.service\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo mv /tmp/kubelet.service /etc/systemd/system/kubelet.service
sudo chown root:root /etc/systemd/system/kubelet.service

while [ 1 ]; do
    rm -f /tmp/kubelet-config.json || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/kubelet-config.json\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo mv /tmp/kubelet-config.json /etc/kubernetes/kubelet/kubelet-config.json
sudo chown root:root /etc/kubernetes/kubelet/kubelet-config.json

sudo systemctl daemon-reload
sudo systemctl disable kubelet

#######
# cache images
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
ISOLATED_REGIONS=${ISOLATED_REGIONS:-us-iso-east-1 us-iso-west-1 us-isob-east-1}
EKS_CACHE_CONTAINER_IMAGES=${EKS_CACHE_CONTAINER_IMAGES:-true}
BINARY_BUCKET_REGION=${BINARY_BUCKET_REGION:-us-west-2}
PAUSE_CONTAINER_VERSION=${PAUSE_CONTAINER_VERSION:-3.5}
KUBERNETES_VERSION=${KUBERNETES_VERSION:-1.26}

if [[ \"$EKS_CACHE_CONTAINER_IMAGES\" == \"true\" ]] && ! [[ ${ISOLATED_REGIONS} =~ $BINARY_BUCKET_REGION ]]; then
    AWS_DOMAIN=$(imds 'latest/meta-data/services/domain')
    ECR_URI=$(/etc/eks/get-ecr-uri.sh \"${BINARY_BUCKET_REGION}\" \"${AWS_DOMAIN}\")

    PAUSE_CONTAINER=\"${ECR_URI}/eks/pause:${PAUSE_CONTAINER_VERSION}\"
    echo \"PAUSE_CONTAINER: ${PAUSE_CONTAINER}\"

    cat /etc/eks/containerd/containerd-config.toml | sed s,SANDBOX_IMAGE,$PAUSE_CONTAINER,g | sudo tee /etc/eks/containerd/containerd-cached-pause-config.toml

    sudo mkdir -p /etc/containerd
    sudo chown -R root:root /etc/containerd
    sudo cp -v /etc/eks/containerd/containerd-cached-pause-config.toml /etc/containerd/config.toml
    sudo cp -v /etc/eks/containerd/sandbox-image.service /etc/systemd/system/sandbox-image.service
    sudo chown root:root /etc/systemd/system/sandbox-image.service

    sudo systemctl daemon-reload
    sudo systemctl restart containerd
    sudo systemctl enable containerd sandbox-image

    # e.g., 1.26
    K8S_MINOR_VERSION=$(echo \"${KUBERNETES_VERSION}\" | cut -d'.' -f1-2)
    echo \"K8S_MINOR_VERSION: ${K8S_MINOR_VERSION}\"

    #### Cache kube-proxy images starting with the addon default version and the latest version
    KUBE_PROXY_ADDON_VERSIONS=$(aws eks describe-addon-versions --addon-name kube-proxy --kubernetes-version=${K8S_MINOR_VERSION})
    echo \"KUBE_PROXY_ADDON_VERSIONS: ${KUBE_PROXY_ADDON_VERSIONS}\"

    KUBE_PROXY_IMGS=()
    if [[ $(jq '.addons | length' <<< $KUBE_PROXY_ADDON_VERSIONS) -gt 0 ]]; then
        DEFAULT_KUBE_PROXY_FULL_VERSION=$(echo \"${KUBE_PROXY_ADDON_VERSIONS}\" | jq -r '.addons[] .addonVersions[] | select(.compatibilities[] .defaultVersion==true).addonVersion')
        DEFAULT_KUBE_PROXY_VERSION=$(echo \"${DEFAULT_KUBE_PROXY_FULL_VERSION}\" | cut -d\"-\" -f1)
        DEFAULT_KUBE_PROXY_PLATFORM_VERSION=$(echo \"${DEFAULT_KUBE_PROXY_FULL_VERSION}\" | cut -d\"-\" -f2)

        LATEST_KUBE_PROXY_FULL_VERSION=$(echo \"${KUBE_PROXY_ADDON_VERSIONS}\" | jq -r '.addons[] .addonVersions[] .addonVersion' | sort -V | tail -n1)
        LATEST_KUBE_PROXY_VERSION=$(echo \"${LATEST_KUBE_PROXY_FULL_VERSION}\" | cut -d\"-\" -f1)
        LATEST_KUBE_PROXY_PLATFORM_VERSION=$(echo \"${LATEST_KUBE_PROXY_FULL_VERSION}\" | cut -d\"-\" -f2)

        KUBE_PROXY_IMGS=(
            ## Default kube-proxy images
            \"${ECR_URI}/eks/kube-proxy:${DEFAULT_KUBE_PROXY_VERSION}-${DEFAULT_KUBE_PROXY_PLATFORM_VERSION}\"
            \"${ECR_URI}/eks/kube-proxy:${DEFAULT_KUBE_PROXY_VERSION}-minimal-${DEFAULT_KUBE_PROXY_PLATFORM_VERSION}\"

            ## Latest kube-proxy images
            \"${ECR_URI}/eks/kube-proxy:${LATEST_KUBE_PROXY_VERSION}-${LATEST_KUBE_PROXY_PLATFORM_VERSION}\"
            \"${ECR_URI}/eks/kube-proxy:${LATEST_KUBE_PROXY_VERSION}-minimal-${LATEST_KUBE_PROXY_PLATFORM_VERSION}\"
        )
    fi
    echo \"KUBE_PROXY_IMGS: ${KUBE_PROXY_IMGS}\"

    #### Cache VPC CNI images starting with the addon default version and the latest version
    VPC_CNI_ADDON_VERSIONS=$(aws eks describe-addon-versions --addon-name vpc-cni --kubernetes-version=${K8S_MINOR_VERSION})
    echo \"VPC_CNI_ADDON_VERSIONS: ${VPC_CNI_ADDON_VERSIONS}\"

    VPC_CNI_IMGS=()
    if [[ $(jq '.addons | length' <<< $VPC_CNI_ADDON_VERSIONS) -gt 0 ]]; then
        DEFAULT_VPC_CNI_VERSION=$(echo \"${VPC_CNI_ADDON_VERSIONS}\" | jq -r '.addons[] .addonVersions[] | select(.compatibilities[] .defaultVersion==true).addonVersion')
        LATEST_VPC_CNI_VERSION=$(echo \"${VPC_CNI_ADDON_VERSIONS}\" | jq -r '.addons[] .addonVersions[] .addonVersion' | sort -V | tail -n1)
        CNI_IMG=\"${ECR_URI}/amazon-k8s-cni\"
        CNI_INIT_IMG=\"${CNI_IMG}-init\"

        VPC_CNI_IMGS=(
            ## Default VPC CNI Images
            \"${CNI_IMG}:${DEFAULT_VPC_CNI_VERSION}\"
            \"${CNI_INIT_IMG}:${DEFAULT_VPC_CNI_VERSION}\"

            ## Latest VPC CNI Images
            \"${CNI_IMG}:${LATEST_VPC_CNI_VERSION}\"
            \"${CNI_INIT_IMG}:${LATEST_VPC_CNI_VERSION}\"
        )
    fi
    echo \"VPC_CNI_IMGS: ${VPC_CNI_IMGS}\"

    CACHE_IMGS=(
        \"${PAUSE_CONTAINER}\"
        ${KUBE_PROXY_IMGS[@]+\"${KUBE_PROXY_IMGS[@]}\"}
        ${VPC_CNI_IMGS[@]+\"${VPC_CNI_IMGS[@]}\"}
    )
    echo \"CACHE_IMGS: ${CACHE_IMGS}\"

    PULLED_IMGS=()
    for img in \"${CACHE_IMGS[@]}\"; do
        ## only kube-proxy-minimal is vended for K8s 1.24+
        if [[ \"${img}\" == *\"kube-proxy:\"* ]] && [[ \"${img}\" != *\"-minimal-\"* ]] && vercmp \"${K8S_MINOR_VERSION}\" gteq \"1.24\"; then
            continue
        fi

        ## Since eksbuild.x version may not match the image tag, we need to decrement the eksbuild version until we find the latest image tag within the app semver
        eksbuild_version=\"1\"
        if [[ ${img} == *'eksbuild.'* ]]; then
            eksbuild_version=$(echo \"${img}\" | grep -o 'eksbuild\\.[0-9]\\+' | cut -d'.' -f2)
        fi

        ## iterate through decrementing the build version each time
        for build_version in $(seq \"${eksbuild_version}\" -1 1); do
            img=$(echo \"${img}\" | sed -E \"s/eksbuild.[0-9]+/eksbuild.${build_version}/\")
            echo \"ctr pulling/fetching an image ${img}\"
            if /etc/eks/containerd/pull-image.sh \"${img}\"; then
                PULLED_IMGS+=(\"${img}\")
                break
            elif [[ \"${build_version}\" -eq 1 ]]; then
                exit 1
            fi
        done
    done
    echo \"PULLED_IMGS: ${PULLED_IMGS}\"

    #### Tag the pulled down image for all other regions in the partition
    for region in $(aws ec2 describe-regions --all-regions | jq -r '.Regions[] .RegionName'); do
        for img in \"${PULLED_IMGS[@]}\"; do
            regional_img=\"${img/$BINARY_BUCKET_REGION/$region}\"
            echo \"tagging a pulled image ${regional_img}\"
            sudo ctr -n k8s.io image tag \"${img}\" \"${regional_img}\" || :

            ## Tag ECR fips endpoint for supported regions
            if [[ \"${region}\" =~ (us-east-1|us-east-2|us-west-1|us-west-2|us-gov-east-1|us-gov-east-2) ]]; then
                regional_fips_img=\"${regional_img/.ecr./.ecr-fips.}\"
                sudo ctr -n k8s.io image tag \"${img}\" \"${regional_fips_img}\" || :
                sudo ctr -n k8s.io image tag \"${img}\" \"${regional_fips_img/-eksbuild.1/}\" || :
            fi

            ## Cache the non-addon VPC CNI images since \"v*.*.*-eksbuild.1\" is equivalent to leaving off the eksbuild suffix
            if [[ \"${img}\" == *\"-cni\"*\"-eksbuild.1\" ]]; then
                sudo ctr -n k8s.io image tag \"${img}\" \"${regional_img/-eksbuild.1/}\" || :
            fi
        done
    done
fi

#######
# write release file
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# 'uname -m' to decide x86_64/aarch64
#######
BASE_AMI_ID=$(imds /latest/meta-data/ami-id)
sudo rm -f /tmp/release-full
cat << EOF > /tmp/release-full
BASE_AMI_ID=$BASE_AMI_ID
BUILD_TIME=$(date)
BUILD_KERNEL=$(uname -r)
ARCH=$(uname -m)

OS_RELEASE_ID=$(. /etc/os-release;echo $ID)
OS_RELEASE_DISTRIBUTION=$(. /etc/os-release;echo $ID$VERSION_ID)

RUNC_VERSION=\"$(runc --version | head -1 | tr -d '\\n')\"
CONTAINERD_VERSION=\"$(containerd --version)\"
CTR_VERSION=\"$(ctr --version)\"

KUBELET_VERSION=\"$(kubelet --version)\"
EOF
cat /tmp/release-full

sudo cp -v /tmp/release-full /etc/release-full
sudo chmod 0444 /etc/release-full
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn eks_worker_node_ami_reuse(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# install EKS worker node AMI (minimum)
# to build on top of the existing ubuntu AMI
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh

#######
# set up nvidia-smi check scripts
# https://github.com/awslabs/amazon-eks-ami/blob/master/files/bootstrap.sh
#######
# https://stackoverflow.com/questions/27920806/how-to-avoid-heredoc-expanding-variables
cat << 'EOF' > /tmp/check-nvidia-smi.sh
#!/usr/bin/env bash

if command -v nvidia-smi &> /dev/null; then
    echo \"INFO: nvidia-smi found\"

    nvidia-smi -q > /tmp/nvidia-smi-check
    if [[ \"$?\" == \"0\" ]]; then
        sudo nvidia-smi -pm 1 # set persistence mode
        sudo nvidia-smi --auto-boost-default=0

        GPUNAME=$(nvidia-smi -L | head -n1)
        echo \"INFO: GPU name: $GPUNAME\"

        # set application clock to maximum
        if [[ $GPUNAME == *\"A100\"* ]]; then
            nvidia-smi -ac 1215,1410
        elif [[ $GPUNAME == *\"V100\"* ]]; then
            nvidia-smi -ac 877,1530
        elif [[ $GPUNAME == *\"K80\"* ]]; then
            nvidia-smi -ac 2505,875
        elif [[ $GPUNAME == *\"T4\"* ]]; then
            nvidia-smi -ac 5001,1590
        elif [[ $GPUNAME == *\"M60\"* ]]; then
            nvidia-smi -ac 2505,1177
        else
            echo \"WARN: unsupported GPU\"
        fi
    else
        echo \"ERROR: nvidia-smi check failed!\"
        cat /tmp/nvidia-smi-check
    fi
else
    echo \"INFO: nvidia-smi NOT found\"
fi
EOF
cat /tmp/check-nvidia-smi.sh
chmod +x /tmp/check-nvidia-smi.sh
sudo mv /tmp/check-nvidia-smi.sh /etc/check-nvidia-smi.sh

#######
# set up files
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /etc/eks
sudo chown -R root:root /etc/eks
sudo mkdir -p /etc/eks/containerd

# https://github.com/awslabs/amazon-eks-ami/commit/7c45ddef58bbb50c869095eeb2185e41a745db6f
targets=(
    containerd-config.toml
    eni-max-pods.txt
    get-ecr-uri.sh
    pull-image.sh
    pull-sandbox-image.sh
    sandbox-image.service
)
for target in \"${targets[@]}\"
do
    while [ 1 ]; do
        rm -f /tmp/${target} || true;
        wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/${target}\"
        if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
        sleep 2s;
    done;
    chmod +x /tmp/${target}
    sudo cp -v /tmp/${target} /etc/eks/containerd/${target}
    sudo mv /tmp/${target} /etc/eks/${target}
done

sudo chown -R root:root /etc/eks
sudo chown -R ubuntu:ubuntu /etc/eks
find /etc/eks

sudo ctr version || true

#######
# set up log-collector for EKS
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /etc/eks
sudo chown -R root:root /etc/eks
sudo mkdir -p /etc/eks/log-collector-script/

while [ 1 ]; do
    rm -f /tmp/eks-log-collector.sh || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/log-collector-script/linux/eks-log-collector.sh\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
chmod +x /tmp/eks-log-collector.sh
sudo mv /tmp/eks-log-collector.sh /etc/eks/log-collector-script/eks-log-collector.sh

sudo chown -R root:root /etc/eks
sudo chown -R ubuntu:ubuntu /etc/eks
find /etc/eks

#######
# set up logrotate for kube-proxy
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
sudo mkdir -p /var/log/journal

while [ 1 ]; do
    rm -f /tmp/logrotate-kube-proxy || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/logrotate-kube-proxy\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo mv /tmp/logrotate-kube-proxy /etc/logrotate.d/kube-proxy
sudo chown root:root /etc/logrotate.d/kube-proxy

while [ 1 ]; do
    rm -f /tmp/logrotate.conf || true;
    wget --quiet --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --tries=70 --directory-prefix=/tmp/ --continue \"https://raw.githubusercontent.com/awslabs/amazon-eks-ami/master/files/logrotate.conf\"
    if [ $? = 0 ]; then break; fi; # check return value, break if successful (0)
    sleep 2s;
done;
sudo mv /tmp/logrotate.conf /etc/logrotate.conf
sudo chown root:root /etc/logrotate.conf

#######
# cache images
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
#######
ISOLATED_REGIONS=${ISOLATED_REGIONS:-us-iso-east-1 us-iso-west-1 us-isob-east-1}
EKS_CACHE_CONTAINER_IMAGES=${EKS_CACHE_CONTAINER_IMAGES:-true}
BINARY_BUCKET_REGION=${BINARY_BUCKET_REGION:-us-west-2}
PAUSE_CONTAINER_VERSION=${PAUSE_CONTAINER_VERSION:-3.5}
KUBERNETES_VERSION=${KUBERNETES_VERSION:-1.26}

if [[ \"$EKS_CACHE_CONTAINER_IMAGES\" == \"true\" ]] && ! [[ ${ISOLATED_REGIONS} =~ $BINARY_BUCKET_REGION ]]; then
    AWS_DOMAIN=$(imds 'latest/meta-data/services/domain')
    ECR_URI=$(/etc/eks/get-ecr-uri.sh \"${BINARY_BUCKET_REGION}\" \"${AWS_DOMAIN}\")

    PAUSE_CONTAINER=\"${ECR_URI}/eks/pause:${PAUSE_CONTAINER_VERSION}\"
    echo \"PAUSE_CONTAINER: ${PAUSE_CONTAINER}\"

    cat /etc/eks/containerd/containerd-config.toml | sed s,SANDBOX_IMAGE,$PAUSE_CONTAINER,g | sudo tee /etc/eks/containerd/containerd-cached-pause-config.toml

    sudo mkdir -p /etc/containerd
    sudo chown -R root:root /etc/containerd
    sudo cp -v /etc/eks/containerd/containerd-cached-pause-config.toml /etc/containerd/config.toml
    sudo cp -v /etc/eks/containerd/sandbox-image.service /etc/systemd/system/sandbox-image.service
    sudo chown root:root /etc/systemd/system/sandbox-image.service

    sudo systemctl daemon-reload
    sudo systemctl restart containerd
    sudo systemctl enable containerd sandbox-image

    # e.g., 1.26
    K8S_MINOR_VERSION=$(echo \"${KUBERNETES_VERSION}\" | cut -d'.' -f1-2)
    echo \"K8S_MINOR_VERSION: ${K8S_MINOR_VERSION}\"

    #### Cache kube-proxy images starting with the addon default version and the latest version
    KUBE_PROXY_ADDON_VERSIONS=$(aws eks describe-addon-versions --addon-name kube-proxy --kubernetes-version=${K8S_MINOR_VERSION})
    echo \"KUBE_PROXY_ADDON_VERSIONS: ${KUBE_PROXY_ADDON_VERSIONS}\"

    KUBE_PROXY_IMGS=()
    if [[ $(jq '.addons | length' <<< $KUBE_PROXY_ADDON_VERSIONS) -gt 0 ]]; then
        DEFAULT_KUBE_PROXY_FULL_VERSION=$(echo \"${KUBE_PROXY_ADDON_VERSIONS}\" | jq -r '.addons[] .addonVersions[] | select(.compatibilities[] .defaultVersion==true).addonVersion')
        DEFAULT_KUBE_PROXY_VERSION=$(echo \"${DEFAULT_KUBE_PROXY_FULL_VERSION}\" | cut -d\"-\" -f1)
        DEFAULT_KUBE_PROXY_PLATFORM_VERSION=$(echo \"${DEFAULT_KUBE_PROXY_FULL_VERSION}\" | cut -d\"-\" -f2)

        LATEST_KUBE_PROXY_FULL_VERSION=$(echo \"${KUBE_PROXY_ADDON_VERSIONS}\" | jq -r '.addons[] .addonVersions[] .addonVersion' | sort -V | tail -n1)
        LATEST_KUBE_PROXY_VERSION=$(echo \"${LATEST_KUBE_PROXY_FULL_VERSION}\" | cut -d\"-\" -f1)
        LATEST_KUBE_PROXY_PLATFORM_VERSION=$(echo \"${LATEST_KUBE_PROXY_FULL_VERSION}\" | cut -d\"-\" -f2)

        KUBE_PROXY_IMGS=(
            ## Default kube-proxy images
            \"${ECR_URI}/eks/kube-proxy:${DEFAULT_KUBE_PROXY_VERSION}-${DEFAULT_KUBE_PROXY_PLATFORM_VERSION}\"
            \"${ECR_URI}/eks/kube-proxy:${DEFAULT_KUBE_PROXY_VERSION}-minimal-${DEFAULT_KUBE_PROXY_PLATFORM_VERSION}\"

            ## Latest kube-proxy images
            \"${ECR_URI}/eks/kube-proxy:${LATEST_KUBE_PROXY_VERSION}-${LATEST_KUBE_PROXY_PLATFORM_VERSION}\"
            \"${ECR_URI}/eks/kube-proxy:${LATEST_KUBE_PROXY_VERSION}-minimal-${LATEST_KUBE_PROXY_PLATFORM_VERSION}\"
        )
    fi
    echo \"KUBE_PROXY_IMGS: ${KUBE_PROXY_IMGS}\"

    #### Cache VPC CNI images starting with the addon default version and the latest version
    VPC_CNI_ADDON_VERSIONS=$(aws eks describe-addon-versions --addon-name vpc-cni --kubernetes-version=${K8S_MINOR_VERSION})
    echo \"VPC_CNI_ADDON_VERSIONS: ${VPC_CNI_ADDON_VERSIONS}\"

    VPC_CNI_IMGS=()
    if [[ $(jq '.addons | length' <<< $VPC_CNI_ADDON_VERSIONS) -gt 0 ]]; then
        DEFAULT_VPC_CNI_VERSION=$(echo \"${VPC_CNI_ADDON_VERSIONS}\" | jq -r '.addons[] .addonVersions[] | select(.compatibilities[] .defaultVersion==true).addonVersion')
        LATEST_VPC_CNI_VERSION=$(echo \"${VPC_CNI_ADDON_VERSIONS}\" | jq -r '.addons[] .addonVersions[] .addonVersion' | sort -V | tail -n1)
        CNI_IMG=\"${ECR_URI}/amazon-k8s-cni\"
        CNI_INIT_IMG=\"${CNI_IMG}-init\"

        VPC_CNI_IMGS=(
            ## Default VPC CNI Images
            \"${CNI_IMG}:${DEFAULT_VPC_CNI_VERSION}\"
            \"${CNI_INIT_IMG}:${DEFAULT_VPC_CNI_VERSION}\"

            ## Latest VPC CNI Images
            \"${CNI_IMG}:${LATEST_VPC_CNI_VERSION}\"
            \"${CNI_INIT_IMG}:${LATEST_VPC_CNI_VERSION}\"
        )
    fi
    echo \"VPC_CNI_IMGS: ${VPC_CNI_IMGS}\"

    CACHE_IMGS=(
        \"${PAUSE_CONTAINER}\"
        ${KUBE_PROXY_IMGS[@]+\"${KUBE_PROXY_IMGS[@]}\"}
        ${VPC_CNI_IMGS[@]+\"${VPC_CNI_IMGS[@]}\"}
    )
    echo \"CACHE_IMGS: ${CACHE_IMGS}\"

    PULLED_IMGS=()
    for img in \"${CACHE_IMGS[@]}\"; do
        ## only kube-proxy-minimal is vended for K8s 1.24+
        if [[ \"${img}\" == *\"kube-proxy:\"* ]] && [[ \"${img}\" != *\"-minimal-\"* ]] && vercmp \"${K8S_MINOR_VERSION}\" gteq \"1.24\"; then
            continue
        fi

        ## Since eksbuild.x version may not match the image tag, we need to decrement the eksbuild version until we find the latest image tag within the app semver
        eksbuild_version=\"1\"
        if [[ ${img} == *'eksbuild.'* ]]; then
            eksbuild_version=$(echo \"${img}\" | grep -o 'eksbuild\\.[0-9]\\+' | cut -d'.' -f2)
        fi

        ## iterate through decrementing the build version each time
        for build_version in $(seq \"${eksbuild_version}\" -1 1); do
            img=$(echo \"${img}\" | sed -E \"s/eksbuild.[0-9]+/eksbuild.${build_version}/\")
            echo \"ctr pulling/fetching an image ${img}\"
            if /etc/eks/containerd/pull-image.sh \"${img}\"; then
                PULLED_IMGS+=(\"${img}\")
                break
            elif [[ \"${build_version}\" -eq 1 ]]; then
                exit 1
            fi
        done
    done
    echo \"PULLED_IMGS: ${PULLED_IMGS}\"

    #### Tag the pulled down image for all other regions in the partition
    for region in $(aws ec2 describe-regions --all-regions | jq -r '.Regions[] .RegionName'); do
        for img in \"${PULLED_IMGS[@]}\"; do
            regional_img=\"${img/$BINARY_BUCKET_REGION/$region}\"
            echo \"tagging a pulled image ${regional_img}\"
            sudo ctr -n k8s.io image tag \"${img}\" \"${regional_img}\" || :

            ## Tag ECR fips endpoint for supported regions
            if [[ \"${region}\" =~ (us-east-1|us-east-2|us-west-1|us-west-2|us-gov-east-1|us-gov-east-2) ]]; then
                regional_fips_img=\"${regional_img/.ecr./.ecr-fips.}\"
                sudo ctr -n k8s.io image tag \"${img}\" \"${regional_fips_img}\" || :
                sudo ctr -n k8s.io image tag \"${img}\" \"${regional_fips_img/-eksbuild.1/}\" || :
            fi

            ## Cache the non-addon VPC CNI images since \"v*.*.*-eksbuild.1\" is equivalent to leaving off the eksbuild suffix
            if [[ \"${img}\" == *\"-cni\"*\"-eksbuild.1\" ]]; then
                sudo ctr -n k8s.io image tag \"${img}\" \"${regional_img/-eksbuild.1/}\" || :
            fi
        done
    done
fi

#######
# write release file
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/install-worker.sh
# 'uname -m' to decide x86_64/aarch64
#######
BASE_AMI_ID=$(imds /latest/meta-data/ami-id)
sudo rm -f /tmp/release-full
cat << EOF > /tmp/release-full
BASE_AMI_ID=$BASE_AMI_ID
BUILD_TIME=$(date)
BUILD_KERNEL=$(uname -r)
ARCH=$(uname -m)

OS_RELEASE_ID=$(. /etc/os-release;echo $ID)
OS_RELEASE_DISTRIBUTION=$(. /etc/os-release;echo $ID$VERSION_ID)

RUNC_VERSION=\"$(runc --version | head -1 | tr -d '\\n')\"
CONTAINERD_VERSION=\"$(containerd --version)\"
CTR_VERSION=\"$(ctr --version)\"

KUBELET_VERSION=\"$(kubelet --version)\"
EOF
cat /tmp/release-full

sudo cp -v /tmp/release-full /etc/release-full
sudo chmod 0444 /etc/release-full
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn aws_key(
    os_type: OsType,
    region: &str,
    aws_secret_key_id: &str,
    aws_secret_access_key: &str,
) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok(format!(
            "
###########################
# writing AWS access key

# NOTE/SECURITY: this must be deleted when building AMI
mkdir -p /home/ubuntu/.aws || true
rm -f /home/ubuntu/.aws/config || true
set +x
cat << EOF > /home/ubuntu/.aws/config
[default]
region = {region}
EOF

rm -f /home/ubuntu/.aws/credentials || true
set +x
cat << EOF > /home/ubuntu/.aws/credentials
[default]
aws_access_key_id = {aws_secret_key_id}
aws_secret_access_key = {aws_secret_access_key}
EOF

set -x
aws sts get-caller-identity
",
        )),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn ami_info(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# print/write AMI info
# 'uname -m' to decide x86_64/aarch64

# sudo find /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl list-units --type=service --no-pager
df -h

BASE_AMI_ID=$(imds /latest/meta-data/ami-id)
sudo rm -f /tmp/release
cat << EOF > /tmp/release
BASE_AMI_ID=$BASE_AMI_ID
BUILD_TIME=$(date)
BUILD_KERNEL=$(uname -r)
ARCH=$(uname -m)
EOF
cat /tmp/release

sudo cp -v /tmp/release /etc/release
sudo chmod 0444 /etc/release
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn cluster_info(s3_bucket: &str, id: &str, data_directory_mounted: bool) -> String {
    if data_directory_mounted {
        format!(
            "
###########################
# write cluster information, assume /data is mounted

echo -n \"{s3_bucket}\" > /data/current_s3_bucket
echo -n \"{id}\" > /data/current_id
"
        )
    } else {
        format!(
            "
###########################
# write cluster information, assume /data is not mounted

echo -n \"{s3_bucket}\" > /tmp/current_s3_bucket
echo -n \"{id}\" > /tmp/current_id
"
        )
    }
}

pub fn cleanup_image_packages(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# clean up packages

sudo apt clean
sudo apt-get clean
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn cleanup_image_tmp_dir(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# clean up /tmp directory

sudo rm -rf /tmp/*
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn cleanup_image_ssh_keys(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# WARN
# clean up image (useful/required for AMI builds)
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/cleanup.sh
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/validate.sh

# sleep enough time for poller
# to grab the successful init completion
sleep 120

sudo rm -rf \\
/etc/ssh/ssh_host* \\
/home/ubuntu/.ssh/authorized_keys \\
/root/.ssh/authorized_keys
"
        .to_string()),
        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}

pub fn cleanup_image_aws_credentials(os_type: OsType) -> io::Result<String> {
    match os_type {
        OsType::Ubuntu2004 | OsType::Ubuntu2204 => Ok("
###########################
# WARN
# clean up AWS credentials
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/cleanup.sh
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/validate.sh

sudo rm -rf /home/ubuntu/.aws
"
        .to_string()),

        OsType::Al2023 => Ok("
###########################
# WARN
# clean up AWS credentials
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/cleanup.sh
# https://github.com/awslabs/amazon-eks-ami/blob/master/scripts/validate.sh

sudo rm -rf /home/ec2-user/.aws
"
        .to_string()),

        _ => Err(Error::new(
            ErrorKind::InvalidInput,
            format!("os_type '{}' not supported", os_type.as_str()),
        )),
    }
}