_common.sh 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. #!/bin/bash
  2. #=================================================
  3. # COMMON VARIABLES
  4. #=================================================
  5. ## new filenames starting 0.00~ynh5
  6. # make a filename/service name from domain/path
  7. if [[ "$path" == /* ]]; then
  8. url_path="${path:1}"
  9. fi
  10. if [[ "__${url_path}__" == '____' ]]; then
  11. flohmarkt_filename="$domain"
  12. else
  13. flohmarkt_filename="$domain-${url_path}"
  14. fi
  15. # this filename is used for logfile name and systemd.service name
  16. # and for symlinking install_dir and data_dir
  17. flohmarkt_filename="${YNH_APP_ID}_${flohmarkt_filename//[^A-Za-z0-9._-]/_}"
  18. # directory flohmarkts software is installed to
  19. # contains ./venv and ./src as sub-directories
  20. flohmarkt_install="$install_dir"
  21. flohmarkt_sym_install="$( dirname $flohmarkt_install )/$flohmarkt_filename"
  22. flohmarkt_venv_dir="${flohmarkt_install}/venv"
  23. flohmarkt_app_dir="${flohmarkt_install}/app"
  24. # directory containing logfiles
  25. flohmarkt_log_dir="/var/log/${app}"
  26. flohmarkt_sym_log_dir="/var/log/${flohmarkt_filename}"
  27. # filename for logfiles - ¡ojo! if not ends with .log will be interpreted
  28. # as a directory by ynh_use_logrotate
  29. # https://github.com/YunoHost/issues/issues/2383
  30. flohmarkt_logfile="${flohmarkt_log_dir}/app.log"
  31. # flohmarkt data_dir
  32. flohmarkt_data_dir="$data_dir"
  33. flohmarkt_sym_data_dir="$( dirname $flohmarkt_data_dir )/$flohmarkt_filename"
  34. ## old filenames before 0.00~ynh5 - for reference and needed to
  35. # migrate (see below)
  36. flohmarkt_old_install="/opt/flohmarkt"
  37. flohmarkt_old_venv_dir="${flohmarkt_old_install}/venv"
  38. flohmarkt_old_app_dir="${flohmarkt_old_install}/flohmarkt"
  39. flohmarkt_old_log_dir="/var/log/flohmarkt/"
  40. flohmarkt_old_service="flohmarkt"
  41. #=================================================
  42. # PERSONAL HELPERS
  43. #=================================================
  44. # debug output
  45. flohmarkt_debug=1
  46. flohmarkt_print_debug() {
  47. if [[ $flohmarkt_debug -eq 1 ]]; then echo "flohmarkt_debug: $*"; fi
  48. }
  49. # Redisgn of ynh_handle_getopts_args for flohmarkt to be tested as `flohmarkt_ynh_handle_getopts_args`
  50. # Internal helper design to allow helpers to use getopts to manage their arguments
  51. #
  52. # [internal]
  53. #
  54. # example: function my_helper()
  55. # {
  56. # local -A args_array=( [a]=arg1= [b]=arg2= [c]=arg3 )
  57. # local arg1
  58. # local arg2
  59. # local arg3
  60. # ynh_handle_getopts_args "$@"
  61. #
  62. # [...]
  63. # }
  64. # my_helper --arg1 "val1" -b val2 -c
  65. #
  66. # usage: ynh_handle_getopts_args "$@"
  67. # | arg: $@ - Simply "$@" to tranfert all the positionnal arguments to the function
  68. #
  69. # This helper need an array, named "args_array" with all the arguments used by the helper
  70. # that want to use ynh_handle_getopts_args
  71. # Be carreful, this array has to be an associative array, as the following example:
  72. # local -A args_array=( [a]=arg1 [b]=arg2= [c]=arg3 )
  73. # Let's explain this array:
  74. # a, b and c are short options, -a, -b and -c
  75. # arg1, arg2 and arg3 are the long options associated to the previous short ones. --arg1, --arg2 and --arg3
  76. # For each option, a short and long version has to be defined.
  77. # Let's see something more significant
  78. # local -A args_array=( [u]=user [f]=finalpath= [d]=database )
  79. #
  80. # NB: Because we're using 'declare' without -g, the array will be declared as a local variable.
  81. #
  82. # Please keep in mind that the long option will be used as a variable to store the values for this option.
  83. # For the previous example, that means that $finalpath will be fill with the value given as argument for this option.
  84. #
  85. # Also, in the previous example, finalpath has a '=' at the end. That means this option need a value.
  86. # So, the helper has to be call with --finalpath /final/path, --finalpath=/final/path or -f /final/path,
  87. # the variable $finalpath will get the value /final/path
  88. # If there's many values for an option, -f /final /path, the value will be separated by a ';' $finalpath=/final;/path
  89. # For an option without value, like --user in the example, the helper can be called only with --user or -u. $user
  90. # will then get the value 1.
  91. #
  92. # To keep a retrocompatibility, a package can still call a helper, using getopts, with positional arguments.
  93. # The "legacy mode" will manage the positional arguments and fill the variable in the same order than they are given
  94. # in $args_array. e.g. for `my_helper "val1" val2`, arg1 will be filled with val1, and arg2 with val2.
  95. # Positional parameters (used to be the only way to use ynh_handle_getopts_args once upon a time) can be
  96. # used also:
  97. #
  98. # '--' start processing the rest of the arguments as positional parameters
  99. # $legacy_args The arguments positional parameters will be assign to
  100. # Needs to be composed of array keys of args_array. If a key for a predefined variable
  101. # is used multiple times the assigned values will be concatenated delimited by ';'.
  102. # If the long option variable to contain the data is predefined as an array (e.g. using
  103. # `local -a arg1` then multiple values will be assigned to its cells.
  104. # If the last positional parameter defined in legacy_args is defined as an array all
  105. # the leftover positional parameters will be assigned to its cells.
  106. # (it is named legacy_args, because the use of positional parameters was about to be
  107. # deprecated before the last re-design of this sub)
  108. #
  109. # Requires YunoHost version 3.2.2 or higher.
  110. # flohmarkt_ynh_handle_getopts_args() {
  111. # TODO testing:
  112. ynh_handle_getopts_args() {
  113. # Manage arguments only if there's some provided
  114. # TODO set +o xtrace # set +x
  115. set +x
  116. if [ $# -eq 0 ]; then
  117. ynh_print_warn --message="ynh_handle_getopts_args called without arguments"
  118. return
  119. fi
  120. # Store arguments in an array to keep each argument separated
  121. local arguments=("$@")
  122. # For each option in the array, reduce to short options for getopts (e.g. for [u]=user, --user will be -u)
  123. # And built parameters string for getopts
  124. # ${!args_array[@]} is the list of all option_flags in the array (An option_flag is 'u' in [u]=user, user is a value)
  125. local getopts_parameters=""
  126. local option_flag=""
  127. ## go through all possible options and replace arguments with short versions
  128. flohmarkt_print_debug "arguments = '${arguments[@]}"
  129. flohmarkt_print_debug "args_array = (${!args_array[@]})"
  130. for option_flag in "${!args_array[@]}"; do
  131. flohmarkt_print_debug "option_flag = $option_flag"
  132. # Concatenate each option_flags of the array to build the string of arguments for getopts
  133. # Will looks like 'abcd' for -a -b -c -d
  134. # If the value of an option_flag finish by =, it's an option with additionnal values.
  135. # (e.g. --user bob or -u bob)
  136. # Check the last character of the value associate to the option_flag
  137. flohmarkt_print_debug "compare to '${args_array[$option_flag]: -1}'"
  138. if [ "${args_array[$option_flag]: -1}" = "=" ]; then
  139. # For an option with additionnal values, add a ':' after the letter for getopts.
  140. getopts_parameters="${getopts_parameters}${option_flag}:"
  141. else
  142. getopts_parameters="${getopts_parameters}${option_flag}"
  143. fi
  144. flohmarkt_print_debug "getopts_parameters = ${getopts_parameters}"
  145. # Check each argument given to the function
  146. local arg=""
  147. # ${#arguments[@]} is the size of the array
  148. ## for one possible option: look at each argument supplied:
  149. for arg in $(seq 0 $((${#arguments[@]} - 1))); do
  150. flohmarkt_print_debug "arg = '$arg', argument = '${arguments[arg]}'"
  151. # the following cases need to be taken care of
  152. # '--arg=value' → works
  153. # '--arg= value' → works
  154. # '--arg=-value' → works
  155. # '--arg= -v' or
  156. # '--arg= --value' → works if not exists arg '[v]=value='
  157. # → $arg will be set to '-v' or '--value'
  158. # but if exists '[v]=value=' this is not the expected behavior:
  159. # → then $arg is expected to contain an empty value and '-v' or '--value'
  160. # is expected to be interpreted as its own valid argument
  161. # (found in use of ynh_replace_string called by ynh_add_config)
  162. # solution:
  163. # insert an empty arg into array arguments to be later interpreted by
  164. # getopts as the missing value to --arg=
  165. # TODO
  166. flohmarkt_print_debug "TODO: {argument[arg]:-1}='${arguments[arg]: -1}'"
  167. if [[ ${arguments[arg]: -1} == '=' ]] \
  168. && [[ "$option_flag" == 'r' ]]
  169. # TODO && ${arguments[arg]} is actual option_flag
  170. Dieser Teil läuft für jedes argument x Mal (jeweils 1x für jedes Element von @args_array.
  171. Wir wollen aber nur einmal die Änderung vornehmen, und zwar genau dann, wenn das aktuelle
  172. option_flag zum aktuellen argument[arg] passt.
  173. then
  174. # arg ends with a '='
  175. local this_argument=${arguments[arg]}
  176. local next_argument=${arguments[arg+1]}
  177. # for looking up next_argument in args_array remove optionally trailing '='
  178. next_argument=$( printf '%s' "$next_argument" | cut -d'=' -f1 )
  179. flohmarkt_print_debug "this_argument='$this_argument', next_argument='$next_argument'"
  180. # check if next_argument is a value in args_array
  181. # → starts with '--' and the rest of the argument excluding optional trailing '='
  182. # of the string is a value in associative array args_array
  183. # → or starts with '-' and the rest of the argument is a valid key in args_array
  184. # (long argument could already have been replaced by short version before)
  185. flohmarkt_print_debug "args_array values='${args_array[@]}'"
  186. flohmarkt_print_debug "args_array keys='${!args_array[@]}'"
  187. flohmarkt_print_debug "{next_argument:2}='${next_argument:2}'"
  188. flohmarkt_print_debug "{next_argument:1:1}='${next_argument:1:1}'"
  189. set -x
  190. if [[ "${next_argument:0:2}" == '--' ]] \
  191. && [[ -n $( printf '%s ' "${args_array[@]}" | fgrep -w "${next_argument:2}" ) ]] \
  192. || [[ "${next_argument:0:1}" == '-' ]] \
  193. && [[ -n $( printf '%s ' "\"${!args_array[@]}\"" | fgrep -w "${next_argument:1:1}" ) ]]
  194. then
  195. # insert an empty value to array arguments to be interpreted as the value
  196. # for argument[arg]
  197. arguments=( ${arguments[@]:0:arg+1} '' ${arguments[@]:arg+1})
  198. flohmarkt_print_debug "now arguments='${arguments[@]}'"
  199. elif [[ ${arguments[arg]} == '--replace_string=' ]] && [[ $option_flag == 'r' ]]; then
  200. exit
  201. fi
  202. fi
  203. # Replace long option with = (match the beginning of the argument)
  204. arguments[arg]="$(printf '%s\n' "${arguments[arg]}" \
  205. | sed "s/^--${args_array[$option_flag]}/-${option_flag}/")"
  206. flohmarkt_print_debug "arg = '$arg', argument = '${arguments[arg]}'"
  207. # And long option without = (match the whole line)
  208. arguments[arg]="$(printf '%s\n' "${arguments[arg]}" \
  209. | sed "s/^--${args_array[$option_flag]%=}$/-${option_flag}/")"
  210. flohmarkt_print_debug "arg = '$arg', argument = '${arguments[arg]}'"
  211. done
  212. flohmarkt_print_debug "arguments = '${arguments[@]}'"
  213. done
  214. flohmarkt_print_debug '================= end first loop ================='
  215. # Parse the first argument, return the number of arguments to be shifted off the arguments array
  216. # The function call is necessary here to allow `getopts` to use $@
  217. parse_arg() {
  218. flohmarkt_print_debug "========= parse_arg started ======== , arguments='$@', getopts_parameters: '$getopts_parameters'"
  219. # Initialize the index of getopts
  220. OPTIND=1
  221. # getopts will fill $parameter with the letter of the option it has read.
  222. local parameter=""
  223. getopts ":$getopts_parameters" parameter || true
  224. flohmarkt_print_debug "after getopts - parameter='$parameter', OPTIND='$OPTIND', OPTARG='$OPTARG'"
  225. if [ "$parameter" = "?" ]; then
  226. ynh_die --message="Invalid argument: -${OPTARG:-}"
  227. flohmarkt_print_debug "Invalid argument: -${OPTARG:-}"
  228. exit 255
  229. elif [ "$parameter" = ":" ]; then
  230. ynh_die --message="-$OPTARG parameter requires an argument."
  231. echo "-$OPTARG parameter requires an argument."
  232. exit 255
  233. else
  234. # Use the long option, corresponding to the short option read by getopts, as a variable
  235. # (e.g. for [u]=user, 'user' will be used as a variable)
  236. # Also, remove '=' at the end of the long option
  237. # The variable name will be stored in 'option_var' as a nameref
  238. option_var="${args_array[$parameter]%=}"
  239. flohmarkt_print_debug "option_var='$option_var'"
  240. # if there's a '=' at the end of the long option name, this option takes values
  241. if [ "${args_array[$parameter]: -1}" != "=" ]; then
  242. # no argument expected for option - set option variable to '1'
  243. option_value=1
  244. else
  245. # remove leading and trailing spaces from OPTARG
  246. OPTARG="$( printf '%s' "${OPTARG}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
  247. option_value="${OPTARG}"
  248. fi
  249. flohmarkt_print_debug "option_value='$option_value'"
  250. # set shift_value according to the number of options interpreted by getopts
  251. shift_value=$(( $OPTIND - 1 ))
  252. flohmarkt_print_debug "shift_value='$shift_value'"
  253. fi
  254. }
  255. # iterate over the arguments: if first argument starts with a '-' feed arguments to getopts
  256. # if first argument doesn't start with a '-' enter mode to read positional parameters
  257. local argument
  258. local positional_mode=0 # state is getopts mode at the beginning, not positional parameters
  259. local positional_count=0 # counter for positional parameters
  260. local option_var='' # the variable name to be filled
  261. # Try to use legacy_args as a list of option_flag of the array args_array
  262. # Otherwise, fill it with getopts_parameters to get the option_flag.
  263. # (But an associative arrays isn't always sorted in the correct order...)
  264. # Remove all ':' in getopts_parameters, if used.
  265. legacy_args=${legacy_args:-${getopts_parameters//:/}}
  266. while [[ -v 'arguments' ]] && [[ ${#arguments} -ne 0 ]]; do
  267. flohmarkt_print_debug '======= start while loop ======='
  268. local shift_value=0
  269. local option_value='' # the value to be filled into ${!option_var}
  270. argument=${arguments[0]}
  271. flohmarkt_print_debug "argument='$argument'"
  272. # if state once changed to positional parameter mode, all the rest of the arguments will
  273. # be interpreted in positional parameter mode even if they start with a '-'
  274. if [ $positional_mode == 0 ] && [ "${argument}" == '--' ];then
  275. flohmarkt_print_debug "found '--', start positional parameter mode"
  276. positional_mode=1
  277. shift_value=1
  278. elif [ $positional_mode == 0 ] && [ "${argument:0:1}" == '-' ]; then
  279. flohmarkt_print_debug "getopts, arguments='${arguments[@]}', starting parse_arg"
  280. parse_arg "${arguments[@]}"
  281. else
  282. positional_mode=1 # set state to positional parameter mode
  283. flohmarkt_print_debug "positional parameter, argument='$argument'"
  284. # Get the option_flag from getopts_parameters by using the option_flag according to the
  285. # position of the argument.
  286. option_flag=${legacy_args:$positional_count:1}
  287. # increment counter for legacy_args if still args left. If no args left check if the
  288. # last arg is a predefined array and let it cells be filled. Otherwise complain and
  289. # return.
  290. flohmarkt_print_debug "positional_counter='$positional_count', max positional_counter='$(( ${#legacy_args} -1 ))'"
  291. if [[ $positional_count -le $((${#legacy_args} - 1)) ]]; then
  292. # set counter to for next option_flag to fill
  293. positional_count=$((positional_count+1))
  294. flohmarkt_print_debug "incremented positional_counter to '$positional_count'"
  295. # Use the long option, corresponding to the option_flag, as a variable
  296. # (e.g. for [u]=user, 'user' will be used as a variable)
  297. # Also, remove '=' at the end of the long option
  298. # The variable name will be stored in 'option_var'
  299. option_var="${args_array[$option_flag]%=}"
  300. elif [[ $positional_count -ge $((${#legacy_args} - 1)) ]] &&
  301. ! declare -p ${option_var} | grep '^declare -a'
  302. then
  303. # no more legacy_args to fill - legacy behaviour: complain and return
  304. ynh_print_warn --message="Too many arguments ! \"${arguments[$i]}\" will be ignored."
  305. return
  306. else
  307. flohmarkt_print_debug "array found - keep going"
  308. fi
  309. # value to be assigned to ${!option_var}
  310. option_value=$argument
  311. # shift off one positional parameter
  312. shift_value=1
  313. fi
  314. # fill option_var with value found
  315. # if ${!option_var} is an array, fill mutiple values as array cells
  316. # otherwise concatenate them seperated by ';'
  317. # TODO explain use of nameref
  318. local -n option_ref=$option_var
  319. flohmarkt_print_debug "option_ref declare: '$(declare -p option_ref)'"
  320. flohmarkt_print_debug "'$option_var' declare: '$(declare -p $option_var)'"
  321. if declare -p $option_var | grep '^declare -a ' > /dev/null; then
  322. # hurray it's an array
  323. flohmarkt_print_debug "hurray! '$option_var' is an array."
  324. ${option_ref}+='("${option_value}")'
  325. elif ! [[ -v "$option_var" ]] || [[ -z "$option_ref" ]]; then
  326. flohmarkt_print_debug "'$option_var' is unset or empty"
  327. option_ref=${option_value}
  328. else
  329. flohmarkt_print_debug "appending to string '$option_ref'"
  330. option_ref+=";${option_value}"
  331. fi
  332. flohmarkt_print_debug "now declared $option_var: '$(declare -p $option_var)'"
  333. # shift value off arguments array
  334. flohmarkt_print_debug "shifting '$shift_value' off arguments='${arguments[@]}'"
  335. arguments=("${arguments[@]:${shift_value}}")
  336. done
  337. # the former subroutine did this - no idea if it is expected somewhere
  338. unset legacy_args
  339. # re-enable trace
  340. set -o xtrace # set -x
  341. }
  342. # local copy of ynh_local_curl() to test some improvement
  343. # https://github.com/YunoHost/issues/issues/2396
  344. # https://codeberg.org/flohmarkt/flohmarkt_ynh/issues/51
  345. ynh_local_curl() {
  346. # Curl abstraction to help with POST requests to local pages (such as installation forms)
  347. #
  348. # usage: ynh_local_curl "page" "key1=value1" "key2=value2" ...
  349. # | arg: -l --line_match: check answer against an extended regex
  350. # | arg: -P --put: PUT instead of POST, requires --data (see below)
  351. # | arg: -H --header: add a header to the request (can be used multiple times)
  352. # | arg: -n --no_sleep: don't sleep 2 seconds (background: https://github.com/YunoHost/yunohost/pull/547)
  353. # | arg: -d --data: data to be PUT or POSTed. Can be used multiple times.
  354. # | arg: -L --location: either the PAGE part in 'https://$domain/$path/PAGE' or an URI
  355. # | arg: -u --user: login username (requires --password)
  356. # | arg: -p --password: login password
  357. # | arg: URL like 'http://doma.in/path/file.ext'
  358. # | arg: page - positional parameter legacy version of '--page'
  359. # | arg: key1=value1 - (Optional, POST only) legacy version of '--data' as positional parameter
  360. # | arg: key2=value2 - (Optional, POST only) Another POST key and corresponding value
  361. # | arg: ... - (Optional, POST only) More POST keys and values
  362. #
  363. # example: ynh_local_curl "/install.php?installButton" "foo=$var1" "bar=$var2"
  364. # → will open a POST request to "https://$domain/$path/install.php?installButton" posting "foo=$var1" and "bar=$var2"
  365. # example: ynh_local_curl -P --header "Accept: application/json" -H "Content-Type: application/json" \
  366. # --data "{\"members\":{\"names\": [\"${app}\"],\"roles\": [\"editor\"]}}" -l '"ok":true' \
  367. # "http://localhost:5984/"
  368. # → will open a POST request to "http://localhost:5984/" adding headers with "Accept: application/json"
  369. # and "Content-Type: application/json" sending the data from the "--data" argument. ynh_local_curl will
  370. # return with an error if the servers response does not match the extended regex '"ok":true'.
  371. #
  372. # For multiple calls, cookies are persisted between each call for the same app.
  373. #
  374. # `$domain` and `$path_url` need to be defined externally if the first form for the 'page' argument is used.
  375. #
  376. # The return code of this function will vary depending of the use of --line_match:
  377. #
  378. # If --line_match has been used the return code will be the one of the grep checking line_match
  379. # against the output of curl. The output of curl will not be returned.
  380. #
  381. # If --line_match has not been provided the return code will be the one of the curl command and
  382. # the output of curl will be echoed.
  383. #
  384. # Requires YunoHost version 2.6.4 or higher.
  385. # Declare an array to define the options of this helper.
  386. local legacy_args=pd
  387. local -A args_array=( [l]=line_match= [P]=put [H]=header= [n]=no_sleep [L]=location= [d]=data= [u]=user= [p]=password= )
  388. local line_match
  389. local put
  390. # @@ todo if the headers contain ';' somewhere it might be a problem to split them
  391. # apart correctly later, because all values are stored in $header seperated by
  392. # ';' like 'header1: value;header2: value'.
  393. # might be a good improvement to 'ynh_handle_getopts_args' to act differently if
  394. # e.g. $header had been defined as an array: https://stackoverflow.com/questions/14525296/how-do-i-check-if-variable-is-an-array
  395. local -a header
  396. local no_sleep
  397. local location
  398. local user
  399. local password
  400. local -a data
  401. local -a curl_opt_args # optional arguments to `curl`
  402. # Manage arguments with getopts
  403. ynh_handle_getopts_args "$@"
  404. # Define url of page to curl
  405. # $location contains either an URL or just a page
  406. local full_page_url
  407. if [[ "$location" =~ ^https?:// ]]; then
  408. # if $location starts with an http-protocol use value as a complete URL
  409. full_page_url="$location"
  410. elif [ "${path_url}" == "/" ]; then
  411. # if $path_url points to the webserver root just append $location to localhost URL
  412. full_page_url="https://localhost$(ynh_normalize_url_path $location)"
  413. else
  414. # else append $path_url and $location to localhost URL
  415. full_page_url="https://localhost${path_url}$(ynh_normalize_url_path $location)"
  416. fi
  417. flohmarkt_print_debug "full_page_url='$full_page_url'"
  418. # Concatenate data
  419. # POST: all elements of array $data in one string seperated by '&'
  420. # PUT: all elements of $data in one string seperated by space
  421. local seperator='&'
  422. if [[ $put -eq 1 ]]; then
  423. seperator=' '
  424. fi
  425. join_by() { local IFS="$1"; shift; echo "$*"; }
  426. local P_DATA=$( join_by "$seperator" ${data[@]} )
  427. if [[ "$P_DATA" != '' ]]; then curl_opt_args+=('--data'); curl_opt_args+=("$P_DATA"); fi
  428. # prepend every element in header array with " -H "
  429. local seq
  430. while [[ $seq -lt ${#header[@]} ]]; do
  431. curl_opt_args+=('-H')
  432. curl_opt_args+=("${header[$seq]}")
  433. seq=$(( $seq + 1 ))
  434. done
  435. # build --user for curl
  436. if [[ -n "$user" ]] && [[ -n "$password" ]]; then
  437. curl_opt_args+=("--user $user:$password")
  438. elif [[ -n "$user" ]] && [[ -z "$password" ]]; then
  439. ynh_die --message="user provided via '-u/--user' needs password specified via '-p/--password'"
  440. fi
  441. flohmarkt_print_debug "long string curl_opt_args='${curl_opt_args[@]}'"
  442. seq=0
  443. while [[ $seq -lt ${#curl_opt_args[@]} ]]; do
  444. flohmarkt_print_debug " opt[$seq]='${curl_opt_args[$seq]}'"
  445. seq=$(( $seq + 1 ))
  446. done
  447. # https://github.com/YunoHost/yunohost/pull/547
  448. # Wait untils nginx has fully reloaded (avoid curl fail with http2) unless disabled
  449. if ! [[ $no_sleep == 1 ]]; then
  450. sleep 2
  451. fi
  452. local cookiefile=/tmp/ynh-$app-cookie.txt
  453. touch $cookiefile
  454. chown root $cookiefile
  455. chmod 700 $cookiefile
  456. # Temporarily enable visitors if needed...
  457. # TODO maybe there's a way to do this using --user and --password instead?
  458. # would improve security
  459. local visitors_enabled=$(ynh_permission_has_user "main" "visitors" && echo yes || echo no)
  460. if [[ $visitors_enabled == "no" ]]; then
  461. ynh_permission_update --permission "main" --add "visitors"
  462. fi
  463. flohmarkt_print_debug executing \'\
  464. curl --silent --show-error --insecure --location --resolve "$domain:443:127.0.0.1" \
  465. --header "Host: $domain" --cookie-jar $cookiefile --cookie $cookiefile \
  466. "${curl_opt_args[@]}" "$full_page_url"\'
  467. # Curl the URL
  468. local curl_result=$( curl --silent --show-error --insecure --location \
  469. --header "Host: $domain" --cookie-jar $cookiefile --cookie $cookiefile \
  470. --resolve "$domain:443:127.0.0.1" "${curl_opt_args[@]}" "$full_page_url" )
  471. local curl_error=$?
  472. flohmarkt_print_debug "curl_result='$curl_result' ($curl_error)"
  473. # check result agains --line_match if provided
  474. if [[ -n $line_match ]]; then
  475. printf '%s' "$curl_result" | grep "$line_match" > /dev/null
  476. # will return the error code of the above grep
  477. else
  478. # no --line_match, return curls error code and output
  479. echo $curl_result
  480. return $curl_error
  481. fi
  482. # re-enable security
  483. if [[ $visitors_enabled == "no" ]]; then
  484. ynh_permission_update --permission "main" --remove "visitors"
  485. fi
  486. }
  487. # create symlinks containing domain and path for install, data and log directories
  488. flohmarkt_ynh_create_symlinks() {
  489. ynh_script_progression --message="Creating symlinks..." --weight=1
  490. ln -s "$flohmarkt_install" "$flohmarkt_sym_install"
  491. ln -s "$flohmarkt_data_dir" "$flohmarkt_sym_data_dir"
  492. ln -s "$flohmarkt_log_dir" "$flohmarkt_sym_log_dir"
  493. true
  494. }
  495. # set file permissions and owner for installation
  496. flohmarkt_ynh_set_permission() {
  497. # install dir - only root needs to write and $app reads
  498. chown root:$app -R "$flohmarkt_install"
  499. chmod g-w,o-rwx -R "$flohmarkt_install"
  500. }
  501. # start flohmarkt service
  502. flohmarkt_ynh_start_service() {
  503. ynh_systemd_action --service_name=$flohmarkt_filename --action="start" \
  504. --line_match='INFO: *Application startup complete.' --log_path="$flohmarkt_logfile" \
  505. --timeout=30
  506. }
  507. # stop flohmarkt service
  508. flohmarkt_ynh_stop_service() {
  509. ynh_systemd_action --service_name=$flohmarkt_filename --action="stop"
  510. }
  511. # start couchdb and wait for success
  512. flohmarkt_ynh_start_couchdb() {
  513. ynh_systemd_action --service_name=couchdb --action="start" --timeout=30 \
  514. --log_path="/var/log/couchdb/couchdb.log" \
  515. --line_match='Apache CouchDB has started on http://127.0.0.1'
  516. }
  517. # stop couchdb
  518. flohmarkt_ynh_stop_couchdb() {
  519. ynh_systemd_action --service_name=couchdb --action="stop" --timeout=30 \
  520. --log_path="/var/log/couchdb/couchdb.log" \
  521. --line_match='SIGTERM received - shutting down'
  522. }
  523. # install or upgrade couchdb
  524. flohmarkt_ynh_up_inst_couchdb() {
  525. echo "\
  526. couchdb couchdb/mode select standalone
  527. couchdb couchdb/mode seen true
  528. couchdb couchdb/bindaddress string 127.0.0.1
  529. couchdb couchdb/bindaddress seen true
  530. couchdb couchdb/cookie string $couchdb_magic_cookie
  531. couchdb couchdb/adminpass password $password_couchdb_admin
  532. couchdb couchdb/adminpass seen true
  533. couchdb couchdb/adminpass_again password $password_couchdb_admin
  534. couchdb couchdb/adminpass_again seen true" | debconf-set-selections
  535. DEBIAN_FRONTEND=noninteractive # apt-get install -y --force-yes couchdb
  536. ynh_install_extra_app_dependencies \
  537. --repo="deb https://apache.jfrog.io/artifactory/couchdb-deb/ $(lsb_release -c -s) main" \
  538. --key="https://couchdb.apache.org/repo/keys.asc" \
  539. --package="couchdb"
  540. }
  541. flohmarkt_ynh_dump_couchdb() {
  542. ../settings/scripts/couchdb-dump/couchdb-dump.sh -b -H 127.0.0.1 -d "${app}" \
  543. -q -u admin -p "${password_couchdb_admin}" -f "${YNH_CWD}/${app}.json"
  544. }
  545. flohmarkt_ynh_import_couchdb() {
  546. ls -l ../settings/scripts/couchdb-dump/couchdb-dump.sh ${YNH_CWD}/${app}.json
  547. ../settings/scripts/couchdb-dump/couchdb-dump.sh -r -c -H 127.0.0.1 -d "${app}" \
  548. -q -u admin -p "${password_couchdb_admin}" -f "${YNH_CWD}/${app}.json"
  549. }
  550. flohmarkt_ynh_delete_couchdb_user() {
  551. # https://codeberg.org/flohmarkt/flohmarkt_ynh/issues/46 - more than one revision?
  552. local couchdb_user_revision=$( curl -sX GET "http://127.0.0.1:5984/_users/org.couchdb.user%3A${app}" \
  553. --user "admin:${password_couchdb_admin}" | jq -r ._rev )
  554. curl -s -X DELETE "http://127.0.0.1:5984/_users/org.couchdb.user%3A${app}?rev=${couchdb_user_revision}" \
  555. --user "admin:${password_couchdb_admin}"
  556. }
  557. flohmarkt_ynh_delete_couchdb_db() {
  558. curl -s -X DELETE "http://127.0.0.1:5984/${app}" --user "admin:${password_couchdb_admin}"
  559. }
  560. flohmarkt_ynh_create_couchdb_user() {
  561. curl -s -X PUT "http://127.0.0.1:5984/_users/org.couchdb.user:${app}" --user "admin:${password_couchdb_admin}"\
  562. -H "Accept: application/json" -H "Content-Type: application/json" \
  563. -d "{\"name\": \"${app}\", \"password\": \"${password_couchdb_flohmarkt}\", \"roles\": [], \"type\": \"user\"}"
  564. # @@ check answer something like
  565. # {"ok":true,"id":"org.couchdb.user:flohmarkt","rev":"35-9865694604ab384388eea0f978a6e728"}
  566. }
  567. flohmarkt_ynh_couchdb_user_permissions() {
  568. curl -s -X PUT "http://127.0.0.1:5984/${app}/_security" --user "admin:${password_couchdb_admin}"\
  569. -H "Accept: application/json" -H "Content-Type: application/json" \
  570. -d "{\"members\":{\"names\": [\"${app}\"],\"roles\": [\"editor\"]}}"
  571. }
  572. flohmarkt_ynh_exists_couchdb_user() {
  573. if [[ $( curl -sX GET "http://127.0.0.1:5984/_users/org.couchdb.user%3A${app}" \
  574. --user "admin:${password_couchdb_admin}" | jq .error ) == '"not_found"' ]]
  575. then
  576. false
  577. else
  578. true
  579. fi
  580. }
  581. flohmarkt_ynh_exists_couchdb_db() {
  582. if [[ $( curl -sX GET "http://127.0.0.1:5984/${app}" --user "admin:${password_couchdb_admin}" \
  583. | jq .error ) == '"not_found"' ]]
  584. then
  585. false
  586. else
  587. true
  588. fi
  589. }
  590. # check whether old couchdb user or database exist before creating the new ones
  591. flohmarkt_ynh_check_old_couchdb() {
  592. if flohmarkt_ynh_exists_couchdb_user; then
  593. ynh_die --ret_code=100 --message="CouchDB user '$app' exists already. Stopping install."
  594. elif flohmarkt_ynh_exists_couchdb_db; then
  595. ynh_die --ret_code=100 --message="CouchDB database '$app' exists already. Stopping install."
  596. fi
  597. }
  598. flohmarkt_ynh_restore_couchdb() {
  599. flohmarkt_ynh_check_old_couchdb
  600. flohmarkt_ynh_import_couchdb
  601. flohmarkt_ynh_create_couchdb_user
  602. flohmarkt_ynh_couchdb_user_permissions
  603. }
  604. # create venv
  605. flohmarkt_ynh_create_venv() {
  606. python3 -m venv --without-pip "$flohmarkt_venv_dir"
  607. }
  608. # install requirements.txt in venv
  609. flohmarkt_ynh_venv_requirements() {
  610. (
  611. set +o nounset
  612. source "$flohmarkt_venv_dir/bin/activate"
  613. set -o nounset
  614. set -x
  615. $flohmarkt_venv_dir/bin/python3 -m ensurepip
  616. $flohmarkt_venv_dir/bin/pip3 install -r "$flohmarkt_app_dir/requirements.txt"
  617. )
  618. }
  619. # move files and directories to their new places
  620. flohmarkt_ynh_upgrade_path_ynh5() {
  621. # flohmarkt and couchdb are already stopped in upgrade script
  622. # move app_dir into new 'app' folder
  623. mv "$flohmarkt_install/flohmarkt" "$flohmarkt_app_dir"
  624. # yunohost seems to move the venv dir automatically, but this
  625. # doesn't work, because the paths inside the venv are not adjusted
  626. # delete the old, not working venv and create a new one:
  627. ynh_secure_remove --file="$flohmarkt_venv_dir"
  628. flohmarkt_ynh_create_venv
  629. flohmarkt_ynh_venv_requirements
  630. # remove old $install_dir
  631. ynh_secure_remove --file="$flohmarkt_old_install"
  632. # move logfile directory
  633. mkdir -p "$flohmarkt_log_dir"
  634. # remove systemd.service - will be generated newly by upgrade
  635. # ynh_remove_systemd_config --service="$flohmarkt_old_service"
  636. ynh_systemd_action --action=stop --service_name="$flohmarkt_old_service"
  637. ynh_systemd_action --action=disable --service_name="$flohmarkt_old_service"
  638. ynh_secure_remove --file="/etc/systemd/system/multi-user.target.wants/flohmarkt.service"
  639. ynh_secure_remove --file="/etc/systemd/system/flohmarkt.service"
  640. # funktioniert nicht? issue?
  641. #ynh_systemd_action --action=daemon-reload
  642. # DEBUG + systemctl daemon-reload flohmarkt
  643. # WARNING Too many arguments.
  644. systemctl daemon-reload
  645. # unit flohmarkt is automatically appended and therefor this fails:
  646. #ynh_systemd_action --action=reset-failed
  647. systemctl reset-failed
  648. # create symlinks
  649. ln -s "$flohmarkt_install" "$flohmarkt_sym_install"
  650. ln -s "$flohmarkt_data_dir" "$flohmarkt_sym_data_dir"
  651. }
  652. #=================================================
  653. # EXPERIMENTAL HELPERS
  654. #=================================================
  655. #=================================================
  656. # FUTURE OFFICIAL HELPERS
  657. #=================================================