_common.sh 38 KB

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