forked from hpi-studyu/studyu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstudyu
executable file
·1919 lines (1713 loc) · 67.6 KB
/
studyu
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
#!/usr/bin/env bash
# This script is a CLI for the StudyU project and wraps the Docker Compose commands.
# It can be used to start and stop the StudyU components and to configure the deployment settings.
# It also provides a way to create a configuration file to store the deployment settings.
# The configuration file is located at .cli_config in the same directory as this script.
# multiselect does not work with "set -e"
set -o pipefail
if [[ "$(head -c 1 <<< "$BASH_VERSION")" -lt 4 ]]; then
echo "Bash version equal or larger than 4 is required to run this script."
exit 1
fi
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
# Color codes for better output
red='\e[0;31m'
green='\e[0;32m'
yellow='\e[1;33m'
blue='\e[1;34m'
purple='\e[0;35m'
bold='\e[1m'
reset='\e[0m'
# Configuration file path
# Check if the STUDYU_CONFIG_FILE environment variable is set
if [ -n "$STUDYU_CONFIG_FILE" ]; then
CONFIG_FILE="$STUDYU_CONFIG_FILE"
else
# Otherwise, fallback to the hardcoded path
CONFIG_FILE="$SCRIPT_DIR/.cli_config"
fi
# Dictionary to map components to Docker Compose files
declare -A compose_files=(
["supabase-db"]="supabase/docker-compose-db.yml"
["supabase"]="supabase/docker-compose.yml"
["studyu-app"]="studyu/docker-compose-app.yml"
["studyu-designer"]="studyu/docker-compose-designer.yml"
["studyu-proxy"]="proxy/docker-compose-proxy.yml"
)
declare -A component_descriptions=(
#["studyu-proxy"]="Necessary to access the components"
#["supabase-db"]="Database storing the Supabase data"
["supabase"]="Supabase provides authentication and storage capabilities for StudyU"
["studyu-app"]="StudyU App (partake in digital studies)"
["studyu-designer"]="StudyU Designer (create and manage studies)"
)
declare -A default_component_values=(
#["studyu-proxy"]="true"
#["supabase-db"]="true"
["supabase"]="true"
["studyu-app"]="true"
["studyu-designer"]="true"
)
postgres_container_name="supabase-db"
postgres_username="postgres"
#database_name="your_database_name"
# Calculate the maximum length of the keys for formatting
max_length=0
for key in "${!component_descriptions[@]}"; do
length=${#key}
if ((length > max_length)); then
max_length=$length
fi
done
selectable_components="${bold}Selectable components:${reset}\n"
for key in "${!component_descriptions[@]}"; do
value="${component_descriptions[$key]}"
spaces=$(printf "%*s" $((max_length - ${#key})) "")
formatted_component=" $key$spaces $value\n"
selectable_components+="$formatted_component"
done
selectable_components+="All components should be specified as a space-separated list. If no components are specified, the default components will be used."
# Function to generate a JWT token for Supabase
# Usage: generate_supabase_jwt <role> <secret>
generate_supabase_jwt() {
local role="${1}"
local secret="${2}"
# Number of seconds for token to expire. Defaults to 5 years (in seconds) as per Supabase docs
local expire_seconds="${3:-31536000}"
local header_base64
local payload_base64
local signed_content
local signature
if [ -z "$role" ] || [ -z "$secret" ]; then
echo -e "${red}Error: Role and secret must be specified.${reset}"
exit 1
fi
# pass JWT_SECRET_BASE64_ENCODED as true if secret is base64 encoded
${JWT_SECRET_BASE64_ENCODED:-false} && \
JWT_SECRET=$(printf %s "$JWT_SECRET" | base64 --decode)
header='{
"alg": "HS256",
"typ": "JWT"
}'
payload="{
\"role\": \"$role\",
\"iss\": \"supabase\",
\"iat\": $(date +%s),
\"exp\": $(($(date +%s) + expire_seconds))
}"
header_base64=$(printf %s "$header" | base64_urlencode)
payload_base64=$(printf %s "$payload" | base64_urlencode)
signed_content="${header_base64}.${payload_base64}"
signature=$(printf %s "$signed_content" | openssl dgst -binary -sha256 -hmac "$secret" | base64_urlencode)
echo "${signed_content}.${signature}"
}
base64_urlencode() { openssl enc -base64 -A | tr '+/' '-_' | tr -d '='; }
# https://unix.stackexchange.com/questions/146570/arrow-key-enter-menu/673436#673436
function multiselect {
# little helpers for terminal print control and key input
ESC=$( printf "\033")
cursor_blink_on() { printf "%s" "${ESC}[?25h"; }
cursor_blink_off() { printf "%s" "${ESC}[?25l"; }
cursor_to() { printf "%s" "${ESC}[$1;${2:-1}H"; }
# shellcheck disable=SC2059
print_inactive() { printf "$2 $1 "; }
# shellcheck disable=SC2059
print_active() { printf "$2 ${ESC}[7m $1 ${ESC}[27m"; }
# shellcheck disable=SC2034
get_cursor_row() { IFS=';' read -srdR -p $'\E[6n' ROW COL; echo "${ROW#*[}"; }
local return_value=$1
local -n options=$2
local -n defaults=$3
local selected=()
for ((i=0; i<${#options[@]}; i++)); do
if [[ ${defaults[i]} = "true" ]]; then
selected+=("true")
else
selected+=("false")
fi
printf "\n"
done
# determine current screen position for overwriting the options
local lastrow
lastrow=$(get_cursor_row)
local startrow
startrow=$((lastrow - ${#options[@]}))
# ensure cursor and input echoing back on upon a ctrl+c during read -s
trap "cursor_blink_on; stty echo; printf '\n'; exit" 2
cursor_blink_off
key_input() {
local key
IFS= read -rsn1 key 2>/dev/null >&2
if [[ $key = "" ]]; then echo enter; fi;
if [[ $key = $'\x20' ]]; then echo space; fi;
if [[ $key = "k" ]]; then echo up; fi;
if [[ $key = "j" ]]; then echo down; fi;
if [[ $key = $'\x1b' ]]; then
read -rsn2 key
if [[ $key = [A || $key = k ]]; then echo up; fi;
if [[ $key = [B || $key = j ]]; then echo down; fi;
fi
}
toggle_option() {
local option=$1
if [[ ${selected[option]} == true ]]; then
selected[option]=false
else
selected[option]=true
fi
}
print_options() {
# print options by overwriting the last lines
local idx=0
for option in "${options[@]}"; do
local prefix="[ ]"
if [[ ${selected[idx]} == true ]]; then
prefix="[\e[38;5;46m✔\e[0m]"
fi
cursor_to $((startrow + idx))
if [ $idx -eq "$1" ]; then
print_active "$option" "$prefix"
else
print_inactive "$option" "$prefix"
fi
((idx++))
done
}
local active=0
while true; do
print_options $active
# user key control
case $(key_input) in
space) toggle_option $active;;
enter) print_options -1; break;;
up) ((active--));
if [ $active -lt 0 ]; then active=$((${#options[@]} - 1)); fi;;
down) ((active++));
if [ "$active" -ge ${#options[@]} ]; then active=0; fi;;
esac
done
# cursor position back to normal
cursor_to "$lastrow"
printf "\n"
cursor_blink_on
eval "$return_value"='("${selected[@]}")'
}
remove_studyu_docker_images() {
local studyu_images
studyu_images=$(docker images -q 'studyu*')
if [ -n "$studyu_images" ]; then
for image in $studyu_images; do
docker rmi "$image" > /dev/null 2>&1
done
fi
}
source_env() {
env_path=$1
if [ ! -f "$env_path" ]; then
echo -e "${red}Error: File $env_path does not exist.${reset}"
exit 1
fi
# shellcheck disable=SC1090
source <(grep -vE '^\s*$|^\s*#' "$env_path")
}
# Function to prompt user with a yes/no question
prompt_yes_no() {
local prompt_text="$1"
local response
while true; do
read -rp "$(echo -e "${purple}$prompt_text${reset} (y/n) ")" response
case $response in
[Yy]* ) return 0;; # Return true for yes
[Nn]* ) return 1;; # Return false for no
* ) echo "Please answer yes or no.";;
esac
done
}
prompt_remove() {
read -rp "$(echo -e "${purple}Enter 'remove' to confirm your choice: ${reset}")" input
if [ "$input" == "remove" ]; then
return 0;
else
return 1;
fi
}
# Define regex patterns for validation
# email_pattern="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
# phone_pattern="^\+?[0-9]+$"
# url_pattern="^[a-zA-Z0-9.-]+(.[a-zA-Z]{2,})?(:[0-9]{1,5})?(/.*)?$"
# text_pattern="^[a-zA-Z]+$"
number_pattern="^[0-9]+$"
# Function to validate if a string matches a regex pattern
is_valid_input() {
local input="$1"
local regex_pattern="$2"
if [[ $input =~ $regex_pattern ]]; then
return 0 # Valid input
else
return 1 # Invalid input
fi
}
# Function to update an environment variable in a file using sed
update_env_variable() {
local file_path="$1"
local variable_name="$2"
local new_value="$3"
local pattern="$4"
if [ -z "$new_value" ] || { [ -n "$pattern" ] && ! is_valid_input "$new_value" "$pattern"; }; then
echo -e "${red}Error: Invalid new value for $variable_name.${reset}"
exit 1
fi
# Enclose the new value in double quotes if it's not already
if [[ "$new_value" != \"*\" ]]; then
new_value=\""$new_value"\"
fi
if [ -f "$file_path" ] && grep -q "^$variable_name=" "$file_path"; then
sed -i "/^$variable_name=/s|.*|$variable_name=$new_value|" "$file_path"
else
echo "$variable_name=$new_value" >> "$file_path"
fi
}
# Function to get an environment variable from a file
get_env_variable() {
local file_path="$1"
local variable_name="$2"
if [ -f "$file_path" ] && grep -q "^$variable_name=" "$file_path"; then
local value
value=$(grep "^$variable_name=" "$file_path" | cut -d '=' -f2- | sed 's/^"\|"$//g')
echo "$value"
fi
}
# Function to generate a random string of variable length
generate_random_string() {
local length="$1"
tr -dc 'a-z0-9' </dev/urandom | head -c "$length"
echo
}
# Function to prompt the user for input with validation
prompt_with_validation() {
local prompt_text="$1"
local input_variable="$2"
local regex_pattern="$3"
while true; do
read -e -rp "$prompt_text: " -i "$input_variable" input_variable
# Check if input is not empty
if [[ -n "$input_variable" ]]; then
# If a regex pattern is provided, check for valid input
if [ -z "$regex_pattern" ] || is_valid_input "$input_variable" "$regex_pattern"; then
echo "$input_variable"
break
fi
fi
done
}
create_specific_env_file() {
local env_path="$1"
if [ ! -f "$env_path" ]; then
cp "$env_path.example" "$env_path"
fi
source_env "$env_path"
#else
# echo -e "${red}Environment file already exists at $env_path${reset}"
}
generate_multilangual_json() {
local -n input_array="$1"
echo '{ "de": "'"${input_array[de]}"'", "en": "'"${input_array[en]}"'" }'
}
generate_contact_json() {
local -n input_array="$1"
echo '{ "email": "'"${input_array[email]}"'", "phone": "'"${input_array[phone]}"'", "website": "'"${input_array[website]}"'", "organization": "'"${input_array[organization]}"'" }'
}
prompt_multilingual() {
local prompt_text="$1"
local -n input_array="$2"
input_array["de"]=$(prompt_with_validation "$prompt_text (German)" "${input_array[de]}")
input_array["en"]=$(prompt_with_validation "$prompt_text (English)" "${input_array[en]}")
}
# Function to prompt user for contact information fields separately
prompt_contact() {
local -n input_array_contact="$1"
input_array_contact["email"]=$(prompt_with_validation "Enter contact email" "${input_array_contact[email]}")
input_array_contact["phone"]=$(prompt_with_validation "Enter contact phone" "${input_array_contact[phone]}")
input_array_contact["website"]=$(prompt_with_validation "Enter contact website" "${input_array_contact[website]}")
input_array_contact["organization"]=$(prompt_with_validation "Enter contact organization" "${input_array_contact[organization]}")
}
# Function to read configuration values from the file
read_config() {
local failOnError="${1:-true}"
# Check if the configuration file does not exist
if [[ ! -f "$CONFIG_FILE" ]]; then
if [[ "$failOnError" == false ]]; then
return 0
else
echo -e "${red}Error: Configuration file not found. Run '$0 config' to create one.${reset}"
exit 1
fi
fi
# Read the configuration file
source_env "$CONFIG_FILE"
# Check if the required variables are present
if [ "$failOnError" = true ] && { [ -z "$STUDYU_DEFAULT_COMPONENTS" ] || [ -z "$STUDYU_PATH" ] || [ -z "$STUDYU_BASE_BRANCH" ]; }; then
echo -e "${red}Error: Configuration file $CONFIG_FILE is missing some entries.${reset}"
echo "Run '$0 config' to set the required options."
exit 1
fi
studyu_env_path="$STUDYU_PATH/flutter_common/lib/envs/.env.local"
supabase_env_path="$STUDYU_PATH/docker/supabase/.env"
proxy_env_path="$STUDYU_PATH/docker/proxy/.env"
if [ "$failOnError" = true ]; then
cd "$STUDYU_PATH/docker/" || exit 1
else
cd "$STUDYU_PATH/docker/" 2>/dev/null || true
fi
}
# Print CLI configuration file
# shellcheck disable=SC2120
print_config() {
local failOnError="${1:-true}"
read_config "$failOnError"
# If the config file exists, display the current configuration
if [ -f "$CONFIG_FILE" ]; then
echo -e "${bold}Content of the StudyU CLI configuration file${reset}\n"
local tmp_file
tmp_file=$(mktemp)
for var in "${!STUDYU@}"; do
echo "$var:${!var}" >> "$tmp_file"
done
column -t -s ':' -c 2 "$tmp_file"
rm "$tmp_file"
echo ""
echo -e "Config file is located at $CONFIG_FILE"
fi
}
# Check if a component is running
component_is_running() {
local component_name="$1"
if ! docker info &>/dev/null; then
echo "Docker daemon is not running."
exit 1
fi
# Check if the container is running using Docker ps command
local container_id
container_id=$(docker ps -q -f name="$component_name")
if [ -z "$container_id" ]; then
# The container is not running
return 1
else
# The container is running
return 0
fi
}
set_default_components() {
local default_components=("${!1}")
# Validate selected components
for component in "${default_components[@]}"; do
if [ ! ${compose_files[$component]+_} ]; then
echo -e "${red}Error: '$component' is not a valid component.${reset}"
exit 1
fi
# Check if component is "supabase" and add "supabase-db"
if [ "$component" == "supabase" ]; then
default_components+=("supabase-db")
fi
# Check if component matches "studyu*" and add "studyu-proxy"
if [[ "$component" == "supabase" || "$component" == "studyu"* ]]; then
default_components+=("studyu-proxy")
fi
done
# Remove duplicates from the array
mapfile -t default_components < <(printf "%s\n" "${default_components[@]}" | sort -u)
# echo "STUDYU_DEFAULT_COMPONENTS=\"${default_components[*]}\"" > "$CONFIG_FILE"
update_env_variable "$CONFIG_FILE" "STUDYU_DEFAULT_COMPONENTS" "${default_components[*]}"
}
set_studyu_path() {
local studyu_path="$1"
# Validate the existence of the path
if [ ! -d "$studyu_path" ]; then
echo -e "${red}Error: The specified path does not exist.${reset}"
exit 1
fi
#echo "STUDYU_PATH=\"$studyu_path\"" >> "$CONFIG_FILE"
update_env_variable "$CONFIG_FILE" "STUDYU_PATH" "$studyu_path"
}
set_studyu_base_branch() {
local base_branch="$1"
#echo "STUDYU_BASE_BRANCH=\"$base_branch\"" >> "$CONFIG_FILE"
update_env_variable "$CONFIG_FILE" "STUDYU_BASE_BRANCH" "$base_branch"
}
set_studyu_secrets_manager() {
local secrets_manager="$1"
# Set the secrets_manager in the configuration file only if it is not empty
if [ -n "$secrets_manager" ]; then
#echo "STUDYU_SECRETS_MANAGER=\"$secrets_manager\"" >> "$CONFIG_FILE"
update_env_variable "$CONFIG_FILE" "STUDYU_SECRETS_MANAGER" "$secrets_manager"
fi
}
declare -A supabase_secrets
create_supabase_secrets() {
postgres_password=$(generate_random_string 40)
jwt_secret=$(generate_random_string 40)
dashboard_username=$(generate_random_string 20)
dashboard_password=$(generate_random_string 20)
anon_key=$(generate_supabase_jwt 'anon' "$jwt_secret")
service_role_key=$(generate_supabase_jwt 'service_role' "$jwt_secret")
supabase_secrets["POSTGRES_PASSWORD"]=$postgres_password
supabase_secrets["JWT_SECRET"]=$jwt_secret
supabase_secrets["DASHBOARD_USERNAME"]=$dashboard_username
supabase_secrets["DASHBOARD_PASSWORD"]=$dashboard_password
supabase_secrets["ANON_KEY"]=$anon_key
supabase_secrets["SERVICE_ROLE_KEY"]=$service_role_key
}
create_and_set_supabase_secrets() {
create_supabase_secrets
update_env_variable "$supabase_env_path" "POSTGRES_PASSWORD" "${supabase_secrets[POSTGRES_PASSWORD]}"
update_env_variable "$supabase_env_path" "JWT_SECRET" "${supabase_secrets[JWT_SECRET]}"
update_env_variable "$supabase_env_path" "ANON_KEY" "${supabase_secrets[ANON_KEY]}"
update_env_variable "$supabase_env_path" "SERVICE_ROLE_KEY" "${supabase_secrets[SERVICE_ROLE_KEY]}"
update_env_variable "$supabase_env_path" "DASHBOARD_USERNAME" "${supabase_secrets[DASHBOARD_USERNAME]}"
update_env_variable "$supabase_env_path" "DASHBOARD_PASSWORD" "${supabase_secrets[DASHBOARD_PASSWORD]}"
}
execute_sql_query() {
local sql_query="$1"
local result
if result=$(docker exec -i "$postgres_container_name" psql -U "$postgres_username" -tAc "$sql_query" | tr -d '\r'); then
return 0
else
echo -e "${red}Error executing SQL query.${reset}"
return 1
fi
}
check_app_config_empty() {
# Execute the query to count rows in the public.app_config table
local result
# we do not want to use execute_sql_query here because we need to check the exit status
result=$(docker exec -t "$postgres_container_name" psql -U "$postgres_username" -tAc "SELECT COUNT(*) FROM public.app_config;" | tr -d '\r')
if ! [[ "$result" =~ ^[0-9]+$ ]]; then
echo -e "${red}Error: Could not execute SQL query.${reset}"
exit 1
fi
if [ "$result" -eq 0 ]; then
echo 0 # Table is empty
else
echo 1 # Table is not empty
fi
}
configure_proxy_env() {
local force_reconfiguration="$1"
if [ -f "$proxy_env_path" ]; then
source_env "$proxy_env_path"
if [ "$force_reconfiguration" != true ]; then
return 0
fi
fi
if component_is_running 'studyu-proxy'; then
if prompt_yes_no "The proxy component needs to be stopped in order to configure it. Do you want to stop and remove it?"; then
down 'studyu-proxy'
else
echo -e "${red}Error: Cannot configure proxy while it is running.${reset}"
exit 1
fi
fi
create_specific_env_file "$proxy_env_path"
while true; do
echo -e "${purple}The StudyU components need a reverse proxy to be accessible. Which hostnames and ports do you want to use?${reset}"
echo "Hostnames only include the domain name, e.g. 'example.com' without 'https://'"
echo "Changing the default settings is only necessary if you want to use a custom hostname or port."
echo "If you do not plan to deploy one of the components, just leave the default settings."
STUDYU_APP_HOST=$(prompt_with_validation "Enter STUDYU_APP_HOST (hostname of the StudyU App)" "$STUDYU_APP_HOST")
STUDYU_APP_PORT=$(prompt_with_validation "Enter STUDYU_APP_PORT (port of the StudyU App)" "$STUDYU_APP_PORT" "$number_pattern")
STUDYU_DESIGNER_HOST=$(prompt_with_validation "Enter STUDYU_DESIGNER_HOST (hostname of the StudyU Designer)" "$STUDYU_DESIGNER_HOST")
STUDYU_DESIGNER_PORT=$(prompt_with_validation "Enter STUDYU_DESIGNER_PORT (port of the StudyU Designer)" "$STUDYU_DESIGNER_PORT" "$number_pattern")
STUDYU_SUPABASE_HOST=$(prompt_with_validation "Enter STUDYU_SUPABASE_HOST (hostname of the Supabase frontend)" "$STUDYU_SUPABASE_HOST")
STUDYU_SUPABASE_PORT=$(prompt_with_validation "Enter STUDYU_SUPABASE_PORT (port of the Supabase frontend)" "$STUDYU_SUPABASE_PORT" "$number_pattern")
echo -e "The StudyU deployment settings will be set as following:"
echo -e " ${bold}STUDYU_APP_HOST=$STUDYU_APP_HOST${reset}"
echo -e " ${bold}STUDYU_APP_PORT=$STUDYU_APP_PORT${reset}"
echo -e " ${bold}STUDYU_DESIGNER_HOST=$STUDYU_DESIGNER_HOST${reset}"
echo -e " ${bold}STUDYU_DESIGNER_PORT=$STUDYU_DESIGNER_PORT${reset}"
echo -e " ${bold}STUDYU_SUPABASE_HOST=$STUDYU_SUPABASE_HOST${reset}"
echo -e " ${bold}STUDYU_SUPABASE_PORT=$STUDYU_SUPABASE_PORT${reset}"
if prompt_yes_no "Do you want to apply these changes?"; then
update_env_variable "$proxy_env_path" "STUDYU_APP_HOST" "$STUDYU_APP_HOST"
update_env_variable "$proxy_env_path" "STUDYU_APP_PORT" "$STUDYU_APP_PORT"
update_env_variable "$proxy_env_path" "STUDYU_DESIGNER_HOST" "$STUDYU_DESIGNER_HOST"
update_env_variable "$proxy_env_path" "STUDYU_DESIGNER_PORT" "$STUDYU_DESIGNER_PORT"
update_env_variable "$proxy_env_path" "STUDYU_SUPABASE_HOST" "$STUDYU_SUPABASE_HOST"
update_env_variable "$proxy_env_path" "STUDYU_SUPABASE_PORT" "$STUDYU_SUPABASE_PORT"
echo -e "${green}Proxy settings have been stored at $proxy_env_path${reset}"
break
fi
done
}
configure_studyu_env() {
local force_reconfiguration="$1"
# this function depends on values from the proxy env
configure_proxy_env
if [ -f "$studyu_env_path" ]; then
source_env "$studyu_env_path"
if [ "$force_reconfiguration" != true ]; then
return 0
fi
fi
# If the StudyU components are running, ask the user if they want to down them
if component_is_running "studyu-app" || component_is_running "studyu-designer"; then
if prompt_yes_no "The StudyU components need to be stopped in order to configure them. Do you want to stop and remove them?"; then
local studyu_components=("studyu-app" "studyu-designer")
down "${studyu_components[@]}"
else
echo -e "${red}Error: Cannot configure Studyu components while they are running.${reset}"
exit 1
fi
fi
while true; do
echo -e "${purple}StudyU needs to connect to a Supabase instance for authentication and storage. Which Supabase instance do you want to use?${reset}"
PS3='Select an option: '
options=("Self-hosted Supabase (using this CLI)" "Default StudyU Supabase" "Use an external StudyU Supabase instance" "Exit")
select opt in "${options[@]}"
do
case $opt in
"${options[0]}")
if [ -f "$supabase_env_path" ]; then
source_env "$supabase_env_path"
anon_key="$ANON_KEY"
fi
if [ -z "$anon_key" ]; then
echo -e "${yellow}You need to configure the 'supabase' component first. Run '$0 config' and add 'supabase' to the list of default components. Afterwards run '$0 start'.${reset}"
continue
fi
local supabase_protocol
echo -e "${purple}Which protocol should be used to access ${reset}${bold}Supabase${reset}${purple}? Please note that using http is highly insecure in a production environment. If you do not deploy your own SSL reverse proxy, just select http as a default.${reset}"
PS3='Select a protocol for Supabase: '
options=("http" "https")
select opt in "${options[@]}"
do
case $opt in
"${options[0]}")
supabase_protocol='http'
break
;;
"${options[1]}")
supabase_protocol='https'
break
;;
*) echo "Invalid option \"$REPLY\". Please enter the number of your option.";;
esac
done
studyu_supabase_url="$supabase_protocol://$STUDYU_SUPABASE_HOST:$STUDYU_SUPABASE_PORT"
break
;;
"${options[1]}")
default_default_env_path="$SCRIPT_DIR/flutter_common/lib/envs/.env"
source_env "$default_default_env_path"
# shellcheck disable=SC2153
studyu_supabase_url="$STUDYU_SUPABASE_URL"
anon_key="$STUDYU_SUPABASE_PUBLIC_ANON_KEY"
break
;;
"${options[2]}")
studyu_supabase_url=$(prompt_with_validation "Enter STUDYU_SUPABASE_URL" "$studyu_supabase_url")
anon_key=$(prompt_with_validation "Enter ANON_KEY" "$anon_key")
break
;;
"${options[3]}")
exit 0
;;
*) echo "Invalid option \"$REPLY\". Please enter the number of your option.";;
esac
done
local studyu_protocol
echo -e "${purple}Which protocol should be used to access ${reset}${bold}StudyU${reset}${purple}? Please note that using http is highly insecure in a production environment. If you do not deploy your own SSL reverse proxy, just select http as a default.${reset}"
PS3='Select a protocol for StudyU: '
options=("http" "https")
select opt in "${options[@]}"
do
case $opt in
"${options[0]}")
studyu_protocol='http'
break
;;
"${options[1]}")
studyu_protocol='https'
break
;;
*) echo "Invalid option \"$REPLY\". Please enter the number of your option.";;
esac
done
studyu_app_url="$studyu_protocol://$STUDYU_APP_HOST:$STUDYU_APP_PORT"
studyu_designer_url="$studyu_protocol://$STUDYU_DESIGNER_HOST:$STUDYU_DESIGNER_PORT"
echo -e "The StudyU settings will be set as following:"
echo -e " ${bold}STUDYU_SUPABASE_URL${reset}=$studyu_supabase_url"
echo -e " ${bold}STUDYU_SUPABASE_PUBLIC_ANON_KEY${reset}=$anon_key"
echo -e " ${bold}STUDYU_APP_URL${reset}=$studyu_app_url"
echo -e " ${bold}STUDYU_DESIGNER_URL${reset}=$studyu_designer_url"
if prompt_yes_no "Do you want to apply these changes?"; then
create_specific_env_file "$studyu_env_path"
update_env_variable "$studyu_env_path" "STUDYU_SUPABASE_URL" "$studyu_supabase_url"
update_env_variable "$studyu_env_path" "STUDYU_SUPABASE_PUBLIC_ANON_KEY" "$anon_key"
update_env_variable "$studyu_env_path" "STUDYU_APP_URL" "$studyu_app_url"
update_env_variable "$studyu_env_path" "STUDYU_DESIGNER_URL" "$studyu_designer_url"
echo -e "${green}StudyU settings have been stored at $studyu_env_path${reset}"
source_env "$studyu_env_path"
break;
fi
done
}
# Function to set configuration options
configure() {
read_config false
# Start the interactive configuration process
echo -e "${bold}StudyU CLI Configurator${reset}"
echo -e "Leave fields blank to use default settings.\n"
# STUDYU_DEFAULT_COMPONENTS
echo -e "${purple}Select the components that should be managed when none are explicitly defined.${reset}"
echo -e "Multiselect help:"
echo -e " j or ↓ => Go down";
echo -e " k or ↑ => Go up";
echo -e " ␣ (Space) => Toggle selection";
echo -e " ↵ (Enter) => Confirm selection\n";
local key_array=("${!component_descriptions[@]}")
#for key in "${!component_descriptions[@]}"; do
# multi_options+=("${bold}$key${reset} - ${component_descriptions[$key]}")
#done
# Set default components to all components if STUDYU_DEFAULT_COMPONENTS is empty
# else use STUDYU_DEFAULT_COMPONENTS
local user_selected_components=("${default_component_values[@]}")
if [ -n "$STUDYU_DEFAULT_COMPONENTS" ]; then
user_selected_components=()
for key in "${!component_descriptions[@]}"; do
if [[ " ${STUDYU_DEFAULT_COMPONENTS[*]} " =~ $key ]]; then
user_selected_components+=("true")
else
user_selected_components+=("false")
fi
done
fi
multiselect result key_array user_selected_components
# Set default components to the selected components
for ((index=0; index<${#key_array[@]}; index++)); do
key=${key_array[$index]}
if [[ "${result[index]}" == true ]]; then
default_components+=("$key")
fi
done
set_default_components default_components[@]
# STUDYU_PATH
studyu_path=${STUDYU_PATH:-$SCRIPT_DIR}
read -i "$studyu_path" -e -rp "$(echo -e "${purple}Enter the path to the StudyU directory${reset} (default: $SCRIPT_DIR): ")" studyu_path
studyu_path=${studyu_path:-$SCRIPT_DIR}
set_studyu_path "$studyu_path"
# STUDYU_BASE_BRANCH
# Set base branch to STUDYU_BASE_BRANCH, if empty to current branch, if empty to main
current_branch=$(cd "$studyu_path" && git rev-parse --abbrev-ref HEAD)
base_branch=${STUDYU_BASE_BRANCH:-$current_branch}
base_branch=${base_branch:-'main'}
read -i "$base_branch" -e -rp "$(echo -e "${purple}Enter the StudyU repository base branch for updating${reset} (default: main): ")" base_branch
base_branch=${base_branch:-'main'}
set_studyu_base_branch "$base_branch"
# STUDYU_SECRETS_MANAGER
secrets_manager=${STUDYU_SECRETS_MANAGER:-''}
read -i "$secrets_manager" -e -rp "$(echo -e "${purple}Enter an optional secrets manager to run with "\''docker compose'\'"${reset} (default: empty): ")" secrets_manager
secrets_manager=${secrets_manager:-''}
set_studyu_secrets_manager "$secrets_manager"
echo -e "${green}Configuration written to $CONFIG_FILE${reset}"
}
# Run docker compose command with optional secrets manager prefix
run_docker_compose() {
local file="$1"
local action="$2"
# todo support this
# local verbose="$3"
# If STUDYU_SECRETS_MANAGER is not empty, use it as the prefix for the Docker Compose command
local compose_command="docker compose -f $file $action"
if [ -n "$STUDYU_SECRETS_MANAGER" ]; then
compose_command="$STUDYU_SECRETS_MANAGER $compose_command"
fi
# Execute the Docker Compose command
# if [ "$verbose" == "--verbose" ]; then
$compose_command
# else
# $compose_command >/dev/null 2>&1
# fi
# Check the exit status of the Docker Compose command and return an error if it failed
local exit_status=$?
if [ "$exit_status" -ne 0 ]; then
echo -e "${red}Error: Docker Compose command failed with exit status $exit_status.${reset}"
# echo -e "Run with --verbose for more information."
exit "$exit_status"
fi
}
clean_flag=false
build_flag=false
init_database_flag=false
init_custom_database_path=''
# Run given docker compose commands such as start/restart/stop
manage_components() {
local action=$1
shift
components=$*
local supabase_installation_success=false
if [ "$clean_flag" = true ]; then
echo -e "${yellow}Option -c detected. Orphan containers will be cleaned up.${reset}"
action+=' --remove-orphans'
fi
# If no components are specified, use the default components
if [ -z "${components[*]}" ]; then
components=("$STUDYU_DEFAULT_COMPONENTS")
fi
# Check if the components are valid
for component in ${components[*]}; do
local compose_file="${compose_files[$component]}"
if [ -z "$compose_file" ]; then
echo -e "${red}Error: Invalid component '$component'${reset}"
echo -e "$selectable_components"
exit 1;
fi
done
# Sort components by their order in the compose_files array
sorted_components=()
for key in "${!compose_files[@]}"; do
if [[ " ${components[*]} " =~ $key ]]; then
sorted_components+=("$key")
fi
done
components=("${sorted_components[@]}")
# Loop through the components and run the Docker Compose command
for component in ${components[*]}; do
local component_specific_action=''
compose_file="${compose_files[$component]}"
echo -e "${blue}Action: $action${reset}"
echo -e "${blue}Component: $component${reset}"
case "$action" in
"up"* )
case "$component" in
"supabase"*)
if [ ! -f "$supabase_env_path" ]; then
echo -e "${green}Created a default Supabase env at $supabase_env_path${reset}"
echo -e "Supabase needs some secrets to ensure a secure usage. Read more about it here: https://supabase.com/docs/guides/functions/secrets"
if prompt_yes_no "Do you want to create these secrets automatically?"; then
create_specific_env_file "$supabase_env_path"
create_and_set_supabase_secrets
echo -e "${green}Generated secrets have been stored in $supabase_env_path${reset}"
supabase_installation_success=true
else
create_specific_env_file "$supabase_env_path"
echo -e "Please open the Supabase env file and modify the default secrets by yourself."
echo -e "The file is located at $supabase_env_path"
echo -e "Have a look at the Supabase documentation if you need any help: https://supabase.com/docs/guides/self-hosting/docker#securing-your-services"
echo -e "Afterwards start the components again."
exit 0
fi
fi
;;
"studyu-proxy")
configure_proxy_env
;;
"studyu-app" | "studyu-designer")
if [ "$build_flag" = true ]; then
echo -e "${yellow}Option -b detected. StudyU components will be built.${reset}"
component_specific_action+=' --build'
fi
configure_studyu_env
;;
esac
;;
"restart" )
;;
"stop" )
;;
"down"* )
;;
* )
echo -e "${red}Error: Invalid action '$action'${reset}"
exit 1
;;
esac
run_docker_compose "$compose_file" "$action""$component_specific_action"
done
# if action is up or restart, wait for components to be running
if [[ "$action" == "up"* ]] || [[ "$action" == "restart" ]]; then
for component in ${components[*]}; do
#until docker inspect --format '{{json .State.Status }}' "$component" | grep -q "running"; do
# echo "Waiting for $component to be running..."
# sleep 3
#done
run_msg="🎉 $component is running"
case "$component" in
"studyu-proxy")
;;
"supabase-db")
# check if container is healthy
until docker inspect --format '{{json .State.Health.Status }}' "$component" | grep -q "healthy"; do
echo "Waiting for $component to be healthy..."
sleep 3
done
# Check if the result is zero (table is empty)
if [ "$(check_app_config_empty)" -eq 0 ]; then
if [ "$init_database_flag" = true ]; then
if [ -n "$init_custom_database_path" ]; then
app_config_sql_path="$init_custom_database_path"
else
app_config_sql_path="$STUDYU_PATH/database/app_config.sql.example"
fi