_common.sh 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. # HELPER DEVELOPMENT for yunohost core
  43. #=================================================
  44. # Redisgn of ynh_handle_getopts_args for flohmarkt to be tested as `flohmarkt_ynh_handle_getopts_args`
  45. # https://github.com/YunoHost/yunohost/pull/1856
  46. # Internal helper design to allow helpers to use getopts to manage their arguments
  47. #
  48. # [internal]
  49. #
  50. # example: function my_helper()
  51. # {
  52. # local -A args_array=( [a]=arg1= [b]=arg2= [c]=arg3 )
  53. # local arg1
  54. # local arg2
  55. # local arg3
  56. # ynh_handle_getopts_args "$@"
  57. #
  58. # [...]
  59. # }
  60. # my_helper --arg1 "val1" -b val2 -c
  61. #
  62. # usage: ynh_handle_getopts_args "$@"
  63. # | arg: $@ - Simply "$@" to tranfert all the positionnal arguments to the function
  64. #
  65. # This helper need an array, named "args_array" with all the arguments used by the helper
  66. # that want to use ynh_handle_getopts_args
  67. # Be carreful, this array has to be an associative array, as the following example:
  68. # local -A args_array=( [a]=arg1 [b]=arg2= [c]=arg3 )
  69. # Let's explain this array:
  70. # a, b and c are short options, -a, -b and -c
  71. # arg1, arg2 and arg3 are the long options associated to the previous short ones. --arg1, --arg2 and --arg3
  72. # For each option, a short and long version has to be defined.
  73. # Let's see something more significant
  74. # local -A args_array=( [u]=user [f]=finalpath= [d]=database )
  75. #
  76. # NB: Because we're using 'declare' without -g, the array will be declared as a local variable.
  77. #
  78. # Please keep in mind that the long option will be used as a variable to store the values for this option.
  79. # For the previous example, that means that $finalpath will be fill with the value given as argument for this option.
  80. #
  81. # Also, in the previous example, finalpath has a '=' at the end. That means this option need a value.
  82. # So, the helper has to be call with --finalpath /final/path, --finalpath=/final/path or -f /final/path,
  83. # the variable $finalpath will get the value /final/path
  84. # If there's many values for an option, -f /final /path, the value will be separated by a ';' $finalpath=/final;/path
  85. # For an option without value, like --user in the example, the helper can be called only with --user or -u. $user
  86. # will then get the value 1.
  87. #
  88. # To keep a retrocompatibility, a package can still call a helper, using getopts, with positional arguments.
  89. # The "legacy mode" will manage the positional arguments and fill the variable in the same order than they are given
  90. # in $args_array. e.g. for `my_helper "val1" val2`, arg1 will be filled with val1, and arg2 with val2.
  91. # Positional parameters (used to be the only way to use ynh_handle_getopts_args once upon a time) can be
  92. # used also:
  93. #
  94. # '--' start processing the rest of the arguments as positional parameters
  95. # $legacy_args The arguments positional parameters will be assign to
  96. # Needs to be composed of array keys of args_array. If a key for a predefined variable
  97. # is used multiple times the assigned values will be concatenated delimited by ';'.
  98. # If the long option variable to contain the data is predefined as an array (e.g. using
  99. # `local -a arg1` then multiple values will be assigned to its cells.
  100. # If the last positional parameter defined in legacy_args is defined as an array all
  101. # the leftover positional parameters will be assigned to its cells.
  102. # (it is named legacy_args, because the use of positional parameters was about to be
  103. # deprecated before the last re-design of this sub)
  104. #
  105. # Requires YunoHost version 3.2.2 or higher.
  106. # ynh_handle_getopts_args() {
  107. flohmarkt_ynh_handle_getopts_args() {
  108. # Manage arguments only if there's some provided
  109. set +o xtrace # set +x
  110. if [ $# -eq 0 ]; then
  111. ynh_print_warn --message="ynh_handle_getopts_args called without arguments"
  112. return
  113. fi
  114. # Store arguments in an array to keep each argument separated
  115. local arguments=("$@")
  116. # For each option in the array, reduce to short options for getopts (e.g. for [u]=user, --user will be -u)
  117. # And built parameters string for getopts
  118. # ${!args_array[@]} is the list of all option_flags in the array (An option_flag is 'u' in [u]=user, user is a value)
  119. local getopts_parameters=""
  120. local option_flag=""
  121. ## go through all possible options and replace arguments with short versions
  122. flohmarkt_print_debug "arguments = '${arguments[@]}"
  123. flohmarkt_print_debug "args_array = (${!args_array[@]})"
  124. for option_flag in "${!args_array[@]}"; do
  125. # TODO refactor: Now I'm not sure anymore this part belongs here. To make the
  126. # this all less hard to read and understand I'm thinking at the moment that it
  127. # would be good to split the different things done here into their own loops:
  128. #
  129. # 1. build the option string $getopts_parameters
  130. # 2. go through the arguments and add empty arguments where needed to
  131. # allow for cases like '--arg= --value' where 'value' is a valid option, too
  132. # 3. replace long option names by short once
  133. # 4. (possibly add empty parameters for '-a -v' in cases where -a expects a value
  134. # and -v is a valid option, too - but I dearly hope this will not be necessary)
  135. flohmarkt_print_debug "option_flag = $option_flag"
  136. # Concatenate each option_flags of the array to build the string of arguments for getopts
  137. # Will looks like 'abcd' for -a -b -c -d
  138. # If the value of an option_flag finish by =, it's an option with additionnal values.
  139. # (e.g. --user bob or -u bob)
  140. # Check the last character of the value associate to the option_flag
  141. flohmarkt_print_debug "compare to '${args_array[$option_flag]: -1}'"
  142. if [ "${args_array[$option_flag]: -1}" = "=" ]; then
  143. # For an option with additionnal values, add a ':' after the letter for getopts.
  144. getopts_parameters="${getopts_parameters}${option_flag}:"
  145. else
  146. getopts_parameters="${getopts_parameters}${option_flag}"
  147. fi
  148. flohmarkt_print_debug "getopts_parameters = ${getopts_parameters}"
  149. # Check each argument given to the function
  150. local arg=""
  151. # ${#arguments[@]} is the size of the array
  152. ## for one possible option: look at each argument supplied:
  153. for arg in $(seq 0 $((${#arguments[@]} - 1))); do
  154. flohmarkt_print_debug "option_flag='$option_flag', arg = '$arg', argument = '${arguments[arg]}'"
  155. # the following cases need to be taken care of
  156. # '--arg=value' → works
  157. # '--arg= value' → works
  158. # '--arg=-value' → works
  159. # '--arg= -v' or
  160. # '--arg= --value' → works if not exists arg '[v]=value='
  161. # → $arg will be set to '-v' or '--value'
  162. # but if exists '[v]=value=' this is not the expected behavior:
  163. # → then $arg is expected to contain an empty value and '-v' or '--value'
  164. # is expected to be interpreted as its own valid argument
  165. # (found in use of ynh_replace_string called by ynh_add_config)
  166. # solution:
  167. # insert an empty arg into array arguments to be later interpreted by
  168. # getopts as the missing value to --arg=
  169. if [[ -v arguments[arg+1] ]] && [[ ${arguments[arg]: -1} == '=' ]]; then
  170. # arg ends with a '='
  171. local this_argument=${arguments[arg]}
  172. local next_argument=${arguments[arg+1]}
  173. # for looking up next_argument in args_array remove optionally trailing '='
  174. next_argument=$( printf '%s' "$next_argument" | cut -d'=' -f1 )
  175. flohmarkt_print_debug "MISSING PARAMETER: this_argument='$this_argument', next_argument='$next_argument'"
  176. # check if next_argument is a value in args_array
  177. # → starts with '--' and the rest of the argument excluding optional trailing '='
  178. # of the string is a value in associative array args_array
  179. # → or starts with '-' and the rest of the argument is a valid key in args_array
  180. # (long argument could already have been replaced by short version before)
  181. flohmarkt_print_debug "args_array values='${args_array[@]}'"
  182. flohmarkt_print_debug "args_array keys='${!args_array[@]}'"
  183. flohmarkt_print_debug "{next_argument:2}='${next_argument:2}'"
  184. flohmarkt_print_debug "{next_argument:0:2}='${next_argument:0:2}'"
  185. if ( [[ "${next_argument:0:2}" == '--' ]] \
  186. && printf '%s ' "${args_array[@]}" | fgrep -w "${next_argument:2}" > /dev/null ) \
  187. || ( [[ "${next_argument:0:1}" == '-' ]] \
  188. && printf '%s ' "${!args_array[@]}" | fgrep -w "${next_argument:1:1}" > /dev/null )
  189. then
  190. # insert an empty value to array arguments to be interpreted as the value
  191. # for argument[arg]
  192. arguments=( ${arguments[@]:0:arg+1} '' ${arguments[@]:arg+1})
  193. flohmarkt_print_debug "now arguments='${arguments[@]}'"
  194. fi
  195. fi
  196. # Replace long option with = (match the beginning of the argument)
  197. arguments[arg]="$(printf '%s\n' "${arguments[arg]}" \
  198. | sed "s/^--${args_array[$option_flag]}/-${option_flag}/")"
  199. # And long option without = (match the whole line)
  200. arguments[arg]="$(printf '%s\n' "${arguments[arg]}" \
  201. | sed "s/^--${args_array[$option_flag]%=}$/-${option_flag}/")"
  202. flohmarkt_print_debug " arg = '$arg', argument = '${arguments[arg]}'"
  203. done
  204. flohmarkt_print_debug "====> end loop: arguments = '${arguments[@]}'"
  205. done
  206. flohmarkt_print_debug '================= end first loop ================='
  207. # Parse the first argument, return the number of arguments to be shifted off the arguments array
  208. # The function call is necessary here to allow `getopts` to use $@
  209. parse_arg() {
  210. flohmarkt_print_debug "========= parse_arg started ======== , arguments='$@', getopts_parameters: '$getopts_parameters'"
  211. # Initialize the index of getopts
  212. OPTIND=1
  213. # getopts will fill $parameter with the letter of the option it has read.
  214. local parameter=""
  215. getopts ":$getopts_parameters" parameter || true
  216. flohmarkt_print_debug "after getopts - parameter='$parameter', OPTIND='${OPTIND:-none}', OPTARG='${OPTARG:-none}'"
  217. if [ "$parameter" = "?" ]; then
  218. ynh_die --message="Invalid argument: -${OPTARG:-}"
  219. flohmarkt_print_debug "Invalid argument: -${OPTARG:-}"
  220. exit 255
  221. elif [ "$parameter" = ":" ]; then
  222. ynh_die --message="-$OPTARG parameter requires an argument."
  223. echo "-$OPTARG parameter requires an argument."
  224. exit 255
  225. else
  226. # Use the long option, corresponding to the short option read by getopts, as a variable
  227. # (e.g. for [u]=user, 'user' will be used as a variable)
  228. # Also, remove '=' at the end of the long option
  229. # The variable name will be stored in 'option_var' as a nameref
  230. option_var="${args_array[$parameter]%=}"
  231. flohmarkt_print_debug "option_var='$option_var'"
  232. # if there's a '=' at the end of the long option name, this option takes values
  233. if [ "${args_array[$parameter]: -1}" != "=" ]; then
  234. # no argument expected for option - set option variable to '1'
  235. option_value=1
  236. else
  237. # remove leading and trailing spaces from OPTARG
  238. OPTARG="$( printf '%s' "${OPTARG}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
  239. option_value="${OPTARG}"
  240. fi
  241. flohmarkt_print_debug "option_value='$option_value'"
  242. # set shift_value according to the number of options interpreted by getopts
  243. shift_value=$(( $OPTIND - 1 ))
  244. flohmarkt_print_debug "shift_value='$shift_value'"
  245. fi
  246. }
  247. # iterate over the arguments: if first argument starts with a '-' feed arguments to getopts
  248. # if first argument doesn't start with a '-' enter mode to read positional parameters
  249. local argument
  250. local positional_mode=0 # state is getopts mode at the beginning, not positional parameters
  251. local positional_count=0 # counter for positional parameters
  252. local option_var='' # the variable name to be filled
  253. # Try to use legacy_args as a list of option_flag of the array args_array
  254. # Otherwise, fill it with getopts_parameters to get the option_flag.
  255. # (But an associative arrays isn't always sorted in the correct order...)
  256. # Remove all ':' in getopts_parameters, if used.
  257. legacy_args=${legacy_args:-${getopts_parameters//:/}}
  258. while [[ -v 'arguments' ]] && [[ ${#arguments} -ne 0 ]]; do
  259. flohmarkt_print_debug '======= start while loop ======='
  260. local shift_value=0
  261. local option_value='' # the value to be filled into ${!option_var}
  262. argument=${arguments[0]}
  263. flohmarkt_print_debug "argument='$argument'"
  264. # if state once changed to positional parameter mode, all the rest of the arguments will
  265. # be interpreted in positional parameter mode even if they start with a '-'
  266. if [ $positional_mode == 0 ] && [ "${argument}" == '--' ];then
  267. flohmarkt_print_debug "found '--', start positional parameter mode"
  268. positional_mode=1
  269. shift_value=1
  270. elif [ $positional_mode == 0 ] && [ "${argument:0:1}" == '-' ]; then
  271. flohmarkt_print_debug "getopts, arguments='${arguments[@]}', starting parse_arg"
  272. parse_arg "${arguments[@]}"
  273. else
  274. positional_mode=1 # set state to positional parameter mode
  275. flohmarkt_print_debug "positional parameter, argument='$argument'"
  276. # Get the option_flag from getopts_parameters by using the option_flag according to the
  277. # position of the argument.
  278. option_flag=${legacy_args:$positional_count:1}
  279. # increment counter for legacy_args if still args left. If no args left check if the
  280. # last arg is a predefined array and let it cells be filled. Otherwise complain and
  281. # return.
  282. flohmarkt_print_debug "positional_counter='$positional_count', max positional_counter='$(( ${#legacy_args} -1 ))'"
  283. if [[ $positional_count -le $((${#legacy_args} - 1)) ]]; then
  284. # set counter to for next option_flag to fill
  285. positional_count=$((positional_count+1))
  286. flohmarkt_print_debug "incremented positional_counter to '$positional_count'"
  287. # Use the long option, corresponding to the option_flag, as a variable
  288. # (e.g. for [u]=user, 'user' will be used as a variable)
  289. # Also, remove '=' at the end of the long option
  290. # The variable name will be stored in 'option_var'
  291. option_var="${args_array[$option_flag]%=}"
  292. elif [[ $positional_count -ge $((${#legacy_args} - 1)) ]] &&
  293. ! declare -p ${option_var} | grep '^declare -a'
  294. then
  295. # no more legacy_args to fill - legacy behaviour: complain and return
  296. ynh_print_warn --message="Too many arguments ! \"${arguments[$i]}\" will be ignored."
  297. return
  298. else
  299. flohmarkt_print_debug "array found - keep going"
  300. fi
  301. # value to be assigned to ${!option_var}
  302. option_value=$argument
  303. # shift off one positional parameter
  304. shift_value=1
  305. fi
  306. # fill option_var with value found
  307. # if ${!option_var} is an array, fill mutiple values as array cells
  308. # otherwise concatenate them seperated by ';'
  309. # nameref is used to access the variable that is named $option_var
  310. local -n option_ref=$option_var
  311. # this defines option_ref as a reference to the variable named "$option_var"
  312. # any operation on option_ref will be written to the variable named "$option_var"
  313. # 'option_ref="hello world"' will work like as if '${!option_var}="hello world"'
  314. # would be a valid syntax
  315. # see also: `man bash` part about commands 'declare' option '-n'
  316. flohmarkt_print_debug "option_ref declare: '$(declare -p option_ref)'"
  317. flohmarkt_print_debug "option_value='$option_value'"
  318. if [[ -v "$option_var" ]] && declare -p $option_var | grep '^declare -a ' > /dev/null; then
  319. # hurray it's an array
  320. flohmarkt_print_debug "hurray! '$option_var' is an array"
  321. option_ref+=( "${option_value}" )
  322. elif ! [[ -v "$option_var" ]] || [[ -z "$option_ref" ]]; then
  323. flohmarkt_print_debug "'$option_var' is unset or empty"
  324. option_ref=${option_value}
  325. else
  326. flohmarkt_print_debug "appending to string '$option_ref'"
  327. option_ref+=";${option_value}"
  328. fi
  329. flohmarkt_print_debug "now declared $option_var: '$(declare -p $option_var)'"
  330. # shift value off arguments array
  331. flohmarkt_print_debug "shifting '$shift_value' off arguments='${arguments[@]}'"
  332. arguments=("${arguments[@]:${shift_value}}")
  333. done
  334. # the former subroutine did this - no idea if it is expected somewhere
  335. unset legacy_args
  336. # re-enable trace
  337. set -o xtrace # set -x
  338. }
  339. # local copy of ynh_local_curl() to test some improvement
  340. # https://github.com/YunoHost/yunohost/pull/1857
  341. # https://github.com/YunoHost/issues/issues/2396
  342. # https://codeberg.org/flohmarkt/flohmarkt_ynh/issues/51
  343. flohmarkt_ynh_local_curl() {
  344. # Curl abstraction to help with POST requests to local pages (such as installation forms)
  345. #
  346. # usage: ynh_local_curl [--option [-other_option […]]] "page" "key1=value1" "key2=value2" ...
  347. # | arg: -l --line_match: check answer against an extended regex
  348. # | arg: -m --method: request method to use: POST (default), PUT, GET, DELETE
  349. # | arg: -H --header: add a header to the request (can be used multiple times)
  350. # | arg: -d --data: data to be PUT or POSTed. Can be used multiple times.
  351. # | arg: -s --seperator: seperator used to concatenate POST/PUT --data or key=value ('none'=no seperator)
  352. # | arg: (default for POST: '&', default for PUT: ' ')
  353. # | arg: -u --user: login username (requires --password)
  354. # | arg: -p --password: login password
  355. # | arg: -n --no_sleep: don't sleep 2 seconds (background: https://github.com/YunoHost/yunohost/pull/547)
  356. # | arg: page - either the PAGE part in 'https://$domain/$path/PAGE' or an URI
  357. # | arg: key1=value1 - (Optional, POST only) legacy version of '--data' as positional parameter
  358. # | arg: key2=value2 - (Optional, POST only) Another POST key and corresponding value
  359. # | arg: ... - (Optional, POST only) More POST keys and values
  360. #
  361. # example: ynh_local_curl "/install.php?installButton" "foo=$var1" "bar=$var2"
  362. # → will open a POST request to "https://$domain/$path/install.php?installButton" posting "foo=$var1" and "bar=$var2"
  363. # example: ynh_local_curl -m POST --header "Accept: application/json" \
  364. # -H "Content-Type: application/json" \
  365. # --data "{\"members\":{\"names\": [\"${app}\"],\"roles\": [\"editor\"]}}" -l '"ok":true' \
  366. # "http://localhost:5984/"
  367. # → will open a POST request to "http://localhost:5984/" adding headers with "Accept: application/json"
  368. # and "Content-Type: application/json" sending the data from the "--data" argument. ynh_local_curl will
  369. # return with an error if the servers response does not match the extended regex '"ok":true'.
  370. #
  371. # For multiple calls, cookies are persisted between each call for the same app.
  372. #
  373. # `$domain` and `$path_url` need to be defined externally if the first form for the 'page' argument is used.
  374. #
  375. # The return code of this function will vary depending of the use of --line_match:
  376. #
  377. # If --line_match has been used the return code will be the one of the grep checking line_match
  378. # against the output of curl. The output of curl will not be returned.
  379. #
  380. # If --line_match has not been provided the return code will be the one of the curl command and
  381. # the output of curl will be echoed.
  382. #
  383. # Requires YunoHost version 2.6.4 or higher.
  384. # Declare an array to define the options of this helper.a
  385. local -A supported_methods=( [PUT]=1 [POST]=1 [GET]=1 [DELETE]=1 )
  386. local legacy_args=Ld
  387. local -A args_array=( [l]=line_match= [m]=method= [H]=header= [n]=no_sleep [L]=location= [d]=data= [u]=user= [p]=password= [s]=seperator= )
  388. local line_match
  389. local method
  390. local -a header
  391. local no_sleep
  392. local location
  393. local user
  394. local password
  395. local seperator
  396. local -a data
  397. local -a curl_opt_args # optional arguments to `curl`
  398. # Manage arguments with getopts
  399. flohmarkt_ynh_handle_getopts_args "$@"
  400. # make sure method is a supported one
  401. if ! [[ -v supported_methods[$method] ]]; then
  402. ynh_die --message="method $method not supported by flohmarkt_ynh_local_curl"
  403. fi
  404. # linter doesn't want that the internal function is used anymore
  405. # it's replaced here quick and dirty
  406. flohmarkt_normalize_url_path() {
  407. # check that $location is a valid '/path'
  408. if [[ -n "${location}" ]]; then
  409. if [ "${location:0:1}" != "/" ]; then
  410. location="/${location}"
  411. fi
  412. if [ "${location:${#location}-1}" == "/" ]; then
  413. location="${location:0:${#location}-1}"
  414. fi
  415. fi
  416. }
  417. # Define url of page to curl
  418. # $location contains either an URL or just a page
  419. local full_page_url
  420. if [[ "$location" =~ ^https?:// ]]; then
  421. # if $location starts with an http-protocol use value as a complete URL
  422. full_page_url="$location"
  423. elif [ "${path_url}" == "/" ]; then
  424. # if $path_url points to the webserver root just append $location to localhost URL
  425. flohmarkt_normalize_url_path
  426. full_page_url="https://localhost${location}"
  427. else
  428. # else append $path_url and $location to localhost URL
  429. flohmarkt_normalize_url_path
  430. full_page_url="https://localhost${path_url}${location}"
  431. fi
  432. flohmarkt_print_debug "full_page_url='$full_page_url'"
  433. # Concatenate data
  434. # POST: all elements of array $data in one string seperated by '&'
  435. # PUT: all elements of $data concatenated in one string
  436. # GET: no data
  437. # DELETE: no data
  438. # if not defined by --seperator set default
  439. if [[ -v seperator ]] && [[ "$seperator" == 'none' ]]; then
  440. seperator=''
  441. elif ! [[ -v seperator ]] && [[ "$method" == 'PUT' ]]; then
  442. seperator=''
  443. elif ! [[ -v seperator ]]; then
  444. seperator='&'
  445. fi
  446. join_by() { local IFS="$1"; shift; echo "$*"; }
  447. local P_DATA=$( join_by "$seperator" ${data[@]} )
  448. if [[ "$P_DATA" != '' ]]; then curl_opt_args+=('--data'); curl_opt_args+=("$P_DATA"); fi
  449. # prepend every element in header array with " -H "
  450. local seq=0
  451. while [[ -v header ]] && [[ $seq -lt ${#header[@]} ]]; do
  452. curl_opt_args+=('-H')
  453. curl_opt_args+=("${header[$seq]}")
  454. seq=$(( $seq + 1 ))
  455. done
  456. # build --user for curl
  457. if [[ -n "$user" ]] && [[ -n "$password" ]]; then
  458. curl_opt_args+=('--user' "$user:$password")
  459. elif [[ -n "$user" ]] && [[ -z "$password" ]]; then
  460. ynh_die --message="user provided via '-u/--user' needs password specified via '-p/--password'"
  461. fi
  462. flohmarkt_print_debug "long string curl_opt_args='${curl_opt_args[@]}'"
  463. seq=0
  464. while [[ $seq -lt ${#curl_opt_args[@]} ]]; do
  465. flohmarkt_print_debug " opt[$seq]='${curl_opt_args[$seq]}'"
  466. seq=$(( $seq + 1 ))
  467. done
  468. # https://github.com/YunoHost/yunohost/pull/547
  469. # Wait untils nginx has fully reloaded (avoid curl fail with http2) unless disabled
  470. if ! [[ -v no_sleep ]]; then
  471. sleep 2
  472. fi
  473. local app=${app:-testing}
  474. local cookiefile=/tmp/ynh-$app-cookie.txt
  475. touch $cookiefile
  476. chown root $cookiefile
  477. chmod 700 $cookiefile
  478. # Temporarily enable visitors if needed...
  479. # TODO maybe there's a way to do this using --user and --password instead?
  480. # would improve security
  481. if ! [[ "$app" == "testing" ]]; then
  482. local visitors_enabled=$(ynh_permission_has_user "main" "visitors" && echo yes || echo no)
  483. if [[ $visitors_enabled == "no" ]]; then
  484. ynh_permission_update --permission "main" --add "visitors"
  485. fi
  486. fi
  487. flohmarkt_print_debug executing \'\
  488. curl --silent --show-error --insecure --location --resolve "$domain:443:127.0.0.1" \
  489. --header "Host: $domain" --cookie-jar $cookiefile --cookie $cookiefile \
  490. "${curl_opt_args[@]}" "$full_page_url"\'
  491. # Curl the URL
  492. local curl_result=$( curl --request "$method" --silent --show-error --insecure --location \
  493. --header "Host: $domain" --cookie-jar $cookiefile --cookie $cookiefile \
  494. --resolve "$domain:443:127.0.0.1" "${curl_opt_args[@]}" "$full_page_url" )
  495. local curl_error=$?
  496. flohmarkt_print_debug "curl_result='$curl_result' ($curl_error)"
  497. # check result agains --line_match if provided
  498. if [[ -v line_match ]] && [[ -n $line_match ]]; then
  499. printf '%s' "$curl_result" | grep "$line_match" > /dev/null
  500. # will return the error code of the above grep
  501. curl_error=$?
  502. else
  503. # no --line_match, return curls error code and output
  504. echo $curl_result
  505. fi
  506. # re-enable security
  507. if [[ -v visitor_enabled ]] && [[ $visitors_enabled == "no" ]]; then
  508. ynh_permission_update --permission "main" --remove "visitors"
  509. fi
  510. return $curl_error
  511. }
  512. #=================================================
  513. # PERSONAL HELPERS
  514. #=================================================
  515. # debug output for flohmarkt_ynh_handle_getopts_args and flohmarkt_ynh_local_curl
  516. # otherwise not needed TODO delete after development of the two is done
  517. flohmarkt_debug=0
  518. flohmarkt_print_debug() {
  519. if [[ $flohmarkt_debug -eq 1 ]]; then echo "flohmarkt_debug: $*" >&2; fi
  520. }
  521. # create symlinks containing domain and path for install, data and log directories
  522. flohmarkt_ynh_create_symlinks() {
  523. ln -s "$flohmarkt_install" "$flohmarkt_sym_install"
  524. ln -s "$flohmarkt_data_dir" "$flohmarkt_sym_data_dir"
  525. ln -s "$flohmarkt_log_dir" "$flohmarkt_sym_log_dir"
  526. true
  527. }
  528. # set file permissions and owner for installation
  529. flohmarkt_ynh_set_permission() {
  530. # venv and app - only root needs to write and $app reads
  531. chown root:$app -R "$flohmarkt_venv_dir"
  532. chmod g-w,o-rwx -R "$flohmarkt_venv_dir"
  533. chown root:$app -R "$flohmarkt_app_dir"
  534. chmod g-w,o-rwx -R "$flohmarkt_app_dir"
  535. }
  536. # start flohmarkt service
  537. flohmarkt_ynh_start_service() {
  538. ynh_systemd_action --service_name=$flohmarkt_filename --action="start" \
  539. --line_match='INFO: *Application startup complete.' --log_path="$flohmarkt_logfile" \
  540. --timeout=30
  541. }
  542. # stop flohmarkt service
  543. flohmarkt_ynh_stop_service() {
  544. ynh_systemd_action --service_name=$flohmarkt_filename --action="stop"
  545. }
  546. # start couchdb and wait for success
  547. flohmarkt_ynh_start_couchdb() {
  548. ynh_systemd_action --service_name=couchdb --action="start" --timeout=30 \
  549. --log_path="/var/log/couchdb/couchdb.log" \
  550. --line_match='Apache CouchDB has started on http://127.0.0.1'
  551. }
  552. # stop couchdb
  553. flohmarkt_ynh_stop_couchdb() {
  554. ynh_systemd_action --service_name=couchdb --action="stop" --timeout=30 \
  555. --log_path="/var/log/couchdb/couchdb.log" \
  556. --line_match='SIGTERM received - shutting down'
  557. }
  558. # install or upgrade couchdb
  559. flohmarkt_ynh_up_inst_couchdb() {
  560. echo "\
  561. couchdb couchdb/mode select standalone
  562. couchdb couchdb/mode seen true
  563. couchdb couchdb/bindaddress string 127.0.0.1
  564. couchdb couchdb/bindaddress seen true
  565. couchdb couchdb/cookie string $couchdb_magic_cookie
  566. couchdb couchdb/adminpass password $password_couchdb_admin
  567. couchdb couchdb/adminpass seen true
  568. couchdb couchdb/adminpass_again password $password_couchdb_admin
  569. couchdb couchdb/adminpass_again seen true" | debconf-set-selections
  570. DEBIAN_FRONTEND=noninteractive # apt-get install -y --force-yes couchdb
  571. ynh_install_extra_app_dependencies \
  572. --repo="deb https://apache.jfrog.io/artifactory/couchdb-deb/ $(lsb_release -c -s) main" \
  573. --key="https://couchdb.apache.org/repo/keys.asc" \
  574. --package="couchdb"
  575. }
  576. # (re)initialise database during install and upgrade
  577. flohmarkt_ynh_initialize_couchdb() {
  578. # run in a sub shell to not source the venv activate to the rest of the script
  579. (
  580. set +o nounset
  581. source "$flohmarkt_venv_dir/bin/activate"
  582. set -o nounset
  583. # change directory to where flohmarkt.conf is located
  584. cd $flohmarkt_app_dir
  585. # initialize_couchdb seems to re-try on connect problems endlessly blocking the yunohost api
  586. # give it 45 seconds to finish and then fail
  587. # https://codeberg.org/ChriChri/flohmarkt_ynh/issues/13
  588. timeout 45 python3 initialize_couchdb.py $password_couchdb_admin
  589. )
  590. }
  591. flohmarkt_ynh_dump_couchdb() {
  592. ../settings/scripts/couchdb-dump/couchdb-dump.sh -b -H 127.0.0.1 -d "${app}" \
  593. -q -u admin -p "${password_couchdb_admin}" -f "${YNH_CWD}/${app}.json"
  594. }
  595. flohmarkt_ynh_import_couchdb() {
  596. ../settings/scripts/couchdb-dump/couchdb-dump.sh -r -c -H 127.0.0.1 -d "${app}" \
  597. -q -u admin -p "${password_couchdb_admin}" -f "${YNH_CWD}/${app}.json"
  598. # TODO: This failed silently during tests when there were leftovers from a former
  599. # install. Check couchdb-dump.sh restore for error codes and handling.
  600. }
  601. flohmarkt_ynh_delete_couchdb_user() {
  602. local couchdb_user_revision=$( flohmarkt_ynh_local_curl -n -m GET -u admin -p "$password_couchdb_admin" \
  603. "http://127.0.0.1:5984/_users/org.couchdb.user%3A${app}" | jq -r ._rev )
  604. if [[ -v couchdb_user_revision ]] && [[ -n "${couchdb_user_revision}" ]]; then
  605. flohmarkt_ynh_local_curl -n -m DELETE -u admin -p ${password_couchdb_admin} -l '"ok":true' \
  606. "http://127.0.0.1:5984/_users/org.couchdb.user%3A${app}?rev=${couchdb_user_revision}"
  607. else
  608. ynh_die --message "couchdb_user_revision is empty (${couchdb_user_revision})"
  609. fi
  610. }
  611. flohmarkt_ynh_create_couchdb_user() {
  612. flohmarkt_ynh_local_curl -n -m PUT -u admin -p "${password_couchdb_admin}" \
  613. -H "Accept: application/json" -H "Content-Type: application/json" \
  614. -d '{' \
  615. -d "\"name\": \"${app}\", \"password\": \"${password_couchdb_flohmarkt}\"," \
  616. -d '"roles": [], "type": "user"}' \
  617. --line_match='"ok":true' \
  618. "http://127.0.0.1:5984/_users/org.couchdb.user:${app}"
  619. }
  620. flohmarkt_ynh_couchdb_user_permissions() {
  621. flohmarkt_ynh_local_curl -n -m PUT -u admin -p "$password_couchdb_admin" \
  622. -H "Accept: application/json" -H "Content-Type: application/json" \
  623. -d "{\"members\":{\"names\": [\"${app}\"],\"roles\": [\"editor\"]}}" \
  624. --line_match='"ok":true' \
  625. "http://127.0.0.1:5984/${app}/_security"
  626. }
  627. flohmarkt_ynh_exists_couchdb_user() {
  628. flohmarkt_ynh_local_curl -n -m GET -u admin -p "$password_couchdb_admin" -l "\"_id\":\"org.couchdb.user:${app}\"" \
  629. "http://127.0.0.1:5984/_users/org.couchdb.user%3A${app}"
  630. }
  631. flohmarkt_ynh_exists_couchdb_db() {
  632. flohmarkt_ynh_local_curl -n -m GET -u admin -p "$password_couchdb_admin" -l "\"db_name\":\"${app}\"" \
  633. "http://127.0.0.1:5984/${app}"
  634. }
  635. flohmarkt_ynh_delete_couchdb_db() {
  636. local legacy_args='n'
  637. local -A args_array=( [n]=name= )
  638. flohmarkt_ynh_handle_getopts_args "$@"
  639. local name=${name:-${app}}
  640. flohmarkt_ynh_local_curl -n -m DELETE -u admin -p "$password_couchdb_admin" \
  641. --line_match='"ok":true' "http://127.0.0.1:5984/${name}"
  642. }
  643. # replicate couchdb to a new database
  644. flohmarkt_ynh_copy_couchdb() {
  645. local legacy_args='on'
  646. local -A args_array=( [o]=old_name= [n]=new_name= )
  647. local new_name
  648. local old_name
  649. flohmarkt_ynh_handle_getopts_args "$@"
  650. old_name=${old_name:-${app}}
  651. flohmarkt_ynh_local_curl -n -m POST -u admin -p "$password_couchdb_admin" \
  652. -H "Accept: application/json" -H "Content-Type: application/json" \
  653. -d '{ "create_target":true,"source" : "' -d"${old_name}" -d'",' \
  654. -d '"target":"' -d "${new_name}" -d'"}' --seperator=none \
  655. --line_match='"ok":true' "http://127.0.0.1:5984/_replicate"
  656. }
  657. # copy couchdb to new name and delete source
  658. flohmarkt_ynh_rename_couchdb() {
  659. local legacy_args='on'
  660. local -A args_array=( [o]=old_name= [n]=new_name= )
  661. local new_name
  662. local old_name
  663. flohmarkt_ynh_handle_getopts_args "$@"
  664. old_name=${old_name:-${app}}
  665. flohmarkt_ynh_copy_couchdb -o "$old_name" -n "$new_name"
  666. flohmarkt_ynh_delete_couchdb_db "$old_name"
  667. }
  668. flohmarkt_ynh_backup_old_couchdb() {
  669. flohmarkt_couchdb_rename_to="${app}_$(date '+%Y-%m-%d_%H-%M-%S_%N')"
  670. if flohmarkt_ynh_rename_couchdb "${app}" "${flohmarkt_couchdb_rename_to}"; then
  671. ynh_print_warn --message="renamed existing database ${app} to ${flohmarkt_couchdb_rename_to}"
  672. else
  673. ynh_die --message="could not rename existing couchdb database and cannot overwrite it"
  674. fi
  675. }
  676. flohmarkt_ynh_restore_couchdb() {
  677. flohmarkt_ynh_import_couchdb
  678. flohmarkt_ynh_create_couchdb_user
  679. flohmarkt_ynh_couchdb_user_permissions
  680. }
  681. # create venv
  682. flohmarkt_ynh_create_venv() {
  683. python3 -m venv --without-pip "$flohmarkt_venv_dir"
  684. }
  685. # install requirements.txt in venv
  686. flohmarkt_ynh_venv_requirements() {
  687. (
  688. set +o nounset
  689. source "$flohmarkt_venv_dir/bin/activate"
  690. set -o nounset
  691. set -x
  692. $flohmarkt_venv_dir/bin/python3 -m ensurepip
  693. $flohmarkt_venv_dir/bin/pip3 install -r "$flohmarkt_app_dir/requirements.txt"
  694. )
  695. }
  696. flohmarkt_ynh_urlwatch_cron() {
  697. mkdir -m 750 -p "${flohmarkt_install}/urlwatch"
  698. chown ${app}:root "${flohmarkt_install}/urlwatch"
  699. ynh_add_config --template="../conf/urlwatch_config.yaml" \
  700. --destination="${flohmarkt_install}/urlwatch/config.yaml"
  701. ynh_add_config --template="../conf/urlwatch_urls.yaml" \
  702. --destination="${flohmarkt_install}/urlwatch/urls.yaml"
  703. ynh_add_config --template="../conf/urlwatch.cron" \
  704. --destination="/etc/cron.hourly/${flohmarkt_filename}"
  705. chown root:root "/etc/cron.hourly/${flohmarkt_filename}"
  706. chmod 755 "/etc/cron.hourly/${flohmarkt_filename}"
  707. # run urlwatch once to initialize if cache file does not exist,
  708. # but if sending email fails (like on CI) just warn
  709. local urlwatch_error
  710. if ! [[ -s /var/www/${app}/urlwatch/cache.file ]] &&
  711. ! ynh_exec_warn sudo -u ${app} urlwatch \
  712. --config=/var/www/${app}/urlwatch/config.yaml \
  713. --urls=/var/www/${app}/urlwatch/urls.yaml \
  714. --cache=/var/www/${app}/urlwatch/cache.file
  715. then
  716. ynh_print_warn --message="initial call to urlwatch failed"
  717. fi
  718. }
  719. flohmarkt_initialized() {
  720. flohmarkt_ynh_local_curl -n -m GET -u admin -p "$password_couchdb_admin" \
  721. -l '"initialized":true' \
  722. "http://127.0.0.1:5984/${app}/instance_settings"
  723. }
  724. flohmarkt_ynh_get_initialization_key() {
  725. flohmarkt_ynh_local_curl -n -m GET -u admin -p "$password_couchdb_admin" \
  726. "http://127.0.0.1:5984/${app}/instance_settings" \
  727. | jq -r .initialization_key
  728. }
  729. # move files and directories to their new places
  730. flohmarkt_ynh_upgrade_path_ynh5() {
  731. # flohmarkt and couchdb are already stopped in upgrade script
  732. # move app_dir into new 'app' folder
  733. mv "$flohmarkt_install/flohmarkt" "$flohmarkt_app_dir"
  734. # yunohost seems to move the venv dir automatically, but this
  735. # doesn't work, because the paths inside the venv are not adjusted
  736. # delete the old, not working venv and create a new one:
  737. ynh_secure_remove --file="$flohmarkt_venv_dir"
  738. flohmarkt_ynh_create_venv
  739. flohmarkt_ynh_venv_requirements
  740. # remove old $install_dir
  741. ynh_secure_remove --file="$flohmarkt_old_install"
  742. # move logfile directory
  743. mkdir -p "$flohmarkt_log_dir"
  744. # remove systemd.service - will be generated newly by upgrade
  745. # ynh_remove_systemd_config --service="$flohmarkt_old_service"
  746. ynh_systemd_action --action=stop --service_name="$flohmarkt_old_service"
  747. ynh_systemd_action --action=disable --service_name="$flohmarkt_old_service"
  748. ynh_secure_remove --file="/etc/systemd/system/multi-user.target.wants/flohmarkt.service"
  749. ynh_secure_remove --file="/etc/systemd/system/flohmarkt.service"
  750. # funktioniert nicht? issue?
  751. #ynh_systemd_action --action=daemon-reload
  752. # DEBUG + systemctl daemon-reload flohmarkt
  753. # WARNING Too many arguments.
  754. systemctl daemon-reload
  755. # unit flohmarkt is automatically appended and therefor this fails:
  756. #ynh_systemd_action --action=reset-failed
  757. systemctl reset-failed
  758. # create symlinks
  759. ln -s "$flohmarkt_install" "$flohmarkt_sym_install"
  760. ln -s "$flohmarkt_data_dir" "$flohmarkt_sym_data_dir"
  761. }
  762. #=================================================
  763. # EXPERIMENTAL HELPERS
  764. #=================================================
  765. #=================================================
  766. # FUTURE OFFICIAL HELPERS
  767. #=================================================