2
0

_common.sh 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. #!/bin/bash
  2. #=================================================
  3. # BACKUP
  4. #=================================================
  5. HUMAN_SIZE () { # Transforme une taille en Ko en une taille lisible pour un humain
  6. human=$(numfmt --to=iec --from-unit=1K $1)
  7. echo $human
  8. }
  9. CHECK_SIZE () { # Vérifie avant chaque backup que l'espace est suffisant
  10. file_to_analyse=$1
  11. backup_size=$(du --summarize "$file_to_analyse" | cut -f1)
  12. free_space=$(df --output=avail "/home/yunohost.backup" | sed 1d)
  13. if [ $free_space -le $backup_size ]
  14. then
  15. ynh_print_err "Espace insuffisant pour sauvegarder $file_to_analyse."
  16. ynh_print_err "Espace disponible: $(HUMAN_SIZE $free_space)"
  17. ynh_die "Espace nécessaire: $(HUMAN_SIZE $backup_size)"
  18. fi
  19. }
  20. #=================================================
  21. # PACKAGE CHECK BYPASSING...
  22. #=================================================
  23. IS_PACKAGE_CHECK () {
  24. return $(env | grep -c container=lxc)
  25. }
  26. #=================================================
  27. # EXPERIMENTAL HELPERS
  28. #=================================================
  29. # Internal helper design to allow helpers to use getopts to manage their arguments
  30. #
  31. # example: function my_helper()
  32. # {
  33. # declare -Ar args_array=( [a]=arg1= [b]=arg2= [c]=arg3 )
  34. # local arg1
  35. # local arg2
  36. # local arg3
  37. # ynh_handle_getopts_args "$@"
  38. #
  39. # [...]
  40. # }
  41. # my_helper --arg1 "val1" -b val2 -c
  42. #
  43. # usage: ynh_handle_getopts_args "$@"
  44. # | arg: $@ - Simply "$@" to tranfert all the positionnal arguments to the function
  45. #
  46. # This helper need an array, named "args_array" with all the arguments used by the helper
  47. # that want to use ynh_handle_getopts_args
  48. # Be carreful, this array has to be an associative array, as the following example:
  49. # declare -Ar args_array=( [a]=arg1 [b]=arg2= [c]=arg3 )
  50. # Let's explain this array:
  51. # a, b and c are short options, -a, -b and -c
  52. # arg1, arg2 and arg3 are the long options associated to the previous short ones. --arg1, --arg2 and --arg3
  53. # For each option, a short and long version has to be defined.
  54. # Let's see something more significant
  55. # declare -Ar args_array=( [u]=user [f]=finalpath= [d]=database )
  56. #
  57. # NB: Because we're using 'declare' without -g, the array will be declared as a local variable.
  58. #
  59. # Please keep in mind that the long option will be used as a variable to store the values for this option.
  60. # For the previous example, that means that $finalpath will be fill with the value given as argument for this option.
  61. #
  62. # Also, in the previous example, finalpath has a '=' at the end. That means this option need a value.
  63. # So, the helper has to be call with --finalpath /final/path, --finalpath=/final/path or -f /final/path, the variable $finalpath will get the value /final/path
  64. # If there's many values for an option, -f /final /path, the value will be separated by a ';' $finalpath=/final;/path
  65. # For an option without value, like --user in the example, the helper can be called only with --user or -u. $user will then get the value 1.
  66. #
  67. # To keep a retrocompatibility, a package can still call a helper, using getopts, with positional arguments.
  68. # The "legacy mode" will manage the positional arguments and fill the variable in the same order than they are given in $args_array.
  69. # e.g. for `my_helper "val1" val2`, arg1 will be filled with val1, and arg2 with val2.
  70. ynh_handle_getopts_args () {
  71. # Manage arguments only if there's some provided
  72. set +x
  73. if [ $# -ne 0 ]
  74. then
  75. # Store arguments in an array to keep each argument separated
  76. local arguments=("$@")
  77. # For each option in the array, reduce to short options for getopts (e.g. for [u]=user, --user will be -u)
  78. # And built parameters string for getopts
  79. # ${!args_array[@]} is the list of all keys in the array (A key is 'u' in [u]=user, user is a value)
  80. local getopts_parameters=""
  81. local key=""
  82. for key in "${!args_array[@]}"
  83. do
  84. # Concatenate each keys of the array to build the string of arguments for getopts
  85. # Will looks like 'abcd' for -a -b -c -d
  86. # If the value of a key finish by =, it's an option with additionnal values. (e.g. --user bob or -u bob)
  87. # Check the last character of the value associate to the key
  88. if [ "${args_array[$key]: -1}" = "=" ]
  89. then
  90. # For an option with additionnal values, add a ':' after the letter for getopts.
  91. getopts_parameters="${getopts_parameters}${key}:"
  92. else
  93. getopts_parameters="${getopts_parameters}${key}"
  94. fi
  95. # Check each argument given to the function
  96. local arg=""
  97. # ${#arguments[@]} is the size of the array
  98. for arg in `seq 0 $(( ${#arguments[@]} - 1 ))`
  99. do
  100. # And replace long option (value of the key) by the short option, the key itself
  101. # (e.g. for [u]=user, --user will be -u)
  102. # Replace long option with =
  103. arguments[arg]="${arguments[arg]//--${args_array[$key]}/-${key} }"
  104. # And long option without =
  105. arguments[arg]="${arguments[arg]//--${args_array[$key]%=}/-${key}}"
  106. done
  107. done
  108. # Read and parse all the arguments
  109. # Use a function here, to use standart arguments $@ and be able to use shift.
  110. parse_arg () {
  111. # Read all arguments, until no arguments are left
  112. while [ $# -ne 0 ]
  113. do
  114. # Initialize the index of getopts
  115. OPTIND=1
  116. # Parse with getopts only if the argument begin by -, that means the argument is an option
  117. # getopts will fill $parameter with the letter of the option it has read.
  118. local parameter=""
  119. getopts ":$getopts_parameters" parameter || true
  120. if [ "$parameter" = "?" ]
  121. then
  122. ynh_die "Invalid argument: -${OPTARG:-}"
  123. elif [ "$parameter" = ":" ]
  124. then
  125. ynh_die "-$OPTARG parameter requires an argument."
  126. else
  127. local shift_value=1
  128. # Use the long option, corresponding to the short option read by getopts, as a variable
  129. # (e.g. for [u]=user, 'user' will be used as a variable)
  130. # Also, remove '=' at the end of the long option
  131. # The variable name will be stored in 'option_var'
  132. local option_var="${args_array[$parameter]%=}"
  133. # If this option doesn't take values
  134. # if there's a '=' at the end of the long option name, this option takes values
  135. if [ "${args_array[$parameter]: -1}" != "=" ]
  136. then
  137. # 'eval ${option_var}' will use the content of 'option_var'
  138. eval ${option_var}=1
  139. else
  140. # Read all other arguments to find multiple value for this option.
  141. # Load args in a array
  142. local all_args=("$@")
  143. # If the first argument is longer than 2 characters,
  144. # There's a value attached to the option, in the same array cell
  145. if [ ${#all_args[0]} -gt 2 ]; then
  146. # Remove the option and the space, so keep only the value itself.
  147. all_args[0]="${all_args[0]#-${parameter} }"
  148. # Reduce the value of shift, because the option has been removed manually
  149. shift_value=$(( shift_value - 1 ))
  150. fi
  151. # Then read the array value per value
  152. for i in `seq 0 $(( ${#all_args[@]} - 1 ))`
  153. do
  154. # If this argument is an option, end here.
  155. if [ "${all_args[$i]:0:1}" == "-" ] || [ -z "${all_args[$i]}" ]
  156. then
  157. # Ignore the first value of the array, which is the option itself
  158. if [ "$i" -ne 0 ]; then
  159. break
  160. fi
  161. else
  162. # Declare the content of option_var as a variable.
  163. eval ${option_var}=""
  164. # Else, add this value to this option
  165. # Each value will be separated by ';'
  166. if [ -n "${!option_var}" ]
  167. then
  168. # If there's already another value for this option, add a ; before adding the new value
  169. eval ${option_var}+="\;"
  170. fi
  171. eval ${option_var}+=\"${all_args[$i]}\"
  172. shift_value=$(( shift_value + 1 ))
  173. fi
  174. done
  175. fi
  176. fi
  177. # Shift the parameter and its argument(s)
  178. shift $shift_value
  179. done
  180. }
  181. # LEGACY MODE
  182. # Check if there's getopts arguments
  183. if [ "${arguments[0]:0:1}" != "-" ]
  184. then
  185. # If not, enter in legacy mode and manage the arguments as positionnal ones.
  186. echo "! Helper used in legacy mode !"
  187. for i in `seq 0 $(( ${#arguments[@]} -1 ))`
  188. do
  189. # Use getopts_parameters as a list of key of the array args_array
  190. # Remove all ':' in getopts_parameters
  191. getopts_parameters=${getopts_parameters//:}
  192. # Get the key from getopts_parameters, by using the key according to the position of the argument.
  193. key=${getopts_parameters:$i:1}
  194. # Use the long option, corresponding to the key, as a variable
  195. # (e.g. for [u]=user, 'user' will be used as a variable)
  196. # Also, remove '=' at the end of the long option
  197. # The variable name will be stored in 'option_var'
  198. local option_var="${args_array[$key]%=}"
  199. # Store each value given as argument in the corresponding variable
  200. # The values will be stored in the same order than $args_array
  201. eval ${option_var}+=\"${arguments[$i]}\"
  202. done
  203. else
  204. # END LEGACY MODE
  205. # Call parse_arg and pass the modified list of args as an array of arguments.
  206. parse_arg "${arguments[@]}"
  207. fi
  208. fi
  209. set -x
  210. }
  211. #=================================================
  212. # Start or restart a service and follow its booting
  213. #
  214. # usage: ynh_check_starting "Line to match" [Log file] [Timeout] [Service name]
  215. #
  216. # | arg: -m, --line_to_match= - Line to match - The line to find in the log to attest the service have finished to boot.
  217. # | arg: -l, --app_log= - Log file - The log file to watch; specify "systemd" to read systemd journal for specified service
  218. # /var/log/$app/$app.log will be used if no other log is defined.
  219. # | arg: -t, --timeout= - Timeout - The maximum time to wait before ending the watching. Defaut 300 seconds.
  220. # | arg: -n, --service_name= - Service name
  221. ynh_check_starting () {
  222. # Declare an array to define the options of this helper.
  223. declare -Ar args_array=( [m]=line_to_match= [l]=app_log= [t]=timeout= [n]=service_name= )
  224. local line_to_match
  225. local app_log
  226. local timeout
  227. local service_name
  228. # Manage arguments with getopts
  229. ynh_handle_getopts_args "$@"
  230. local app_log="${app_log:-/var/log/$service_name/$service_name.log}"
  231. local timeout=${timeout:-300}
  232. local service_name="${service_name:-$app}"
  233. echo "Starting of $service_name" >&2
  234. systemctl stop $service_name
  235. local templog="$(mktemp)"
  236. # Following the starting of the app in its log
  237. if [ "$app_log" == "systemd" ] ; then
  238. # Read the systemd journal
  239. journalctl -u $service_name -f --since=-45 > "$templog" &
  240. else
  241. # Read the specified log file
  242. tail -F -n0 "$app_log" > "$templog" &
  243. fi
  244. # Get the PID of the last command
  245. local pid_tail=$!
  246. systemctl start $service_name
  247. local i=0
  248. for i in `seq 1 $timeout`
  249. do
  250. # Read the log until the sentence is found, which means the app finished starting. Or run until the timeout.
  251. if grep --quiet "$line_to_match" "$templog"
  252. then
  253. echo "The service $service_name has correctly started." >&2
  254. break
  255. fi
  256. echo -n "." >&2
  257. sleep 1
  258. done
  259. if [ $i -eq $timeout ]
  260. then
  261. echo "The service $service_name didn't fully start before the timeout." >&2
  262. fi
  263. echo ""
  264. ynh_clean_check_starting
  265. }
  266. # Clean temporary process and file used by ynh_check_starting
  267. # (usually used in ynh_clean_setup scripts)
  268. #
  269. # usage: ynh_clean_check_starting
  270. ynh_clean_check_starting () {
  271. # Stop the execution of tail.
  272. kill -s 15 $pid_tail 2>&1
  273. ynh_secure_remove "$templog" 2>&1
  274. }
  275. #=================================================
  276. ynh_print_log () {
  277. echo "${1}"
  278. }
  279. # Print an info on stdout
  280. #
  281. # usage: ynh_print_info "Text to print"
  282. # | arg: text - The text to print
  283. ynh_print_info () {
  284. ynh_print_log "[INFO] ${1}"
  285. }
  286. # Print a warning on stderr
  287. #
  288. # usage: ynh_print_warn "Text to print"
  289. # | arg: text - The text to print
  290. ynh_print_warn () {
  291. ynh_print_log "[WARN] ${1}" >&2
  292. }
  293. # Print a error on stderr
  294. #
  295. # usage: ynh_print_err "Text to print"
  296. # | arg: text - The text to print
  297. ynh_print_err () {
  298. ynh_print_log "[ERR] ${1}" >&2
  299. }
  300. # Execute a command and print the result as an error
  301. #
  302. # usage: ynh_exec_err command to execute
  303. # usage: ynh_exec_err "command to execute | following command"
  304. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  305. #
  306. # | arg: command - command to execute
  307. ynh_exec_err () {
  308. ynh_print_err "$(eval $@)"
  309. }
  310. # Execute a command and print the result as a warning
  311. #
  312. # usage: ynh_exec_warn command to execute
  313. # usage: ynh_exec_warn "command to execute | following command"
  314. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  315. #
  316. # | arg: command - command to execute
  317. ynh_exec_warn () {
  318. ynh_print_warn "$(eval $@)"
  319. }
  320. # Execute a command and force the result to be printed on stdout
  321. #
  322. # usage: ynh_exec_warn_less command to execute
  323. # usage: ynh_exec_warn_less "command to execute | following command"
  324. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  325. #
  326. # | arg: command - command to execute
  327. ynh_exec_warn_less () {
  328. eval $@ 2>&1
  329. }
  330. # Execute a command and redirect stdout in /dev/null
  331. #
  332. # usage: ynh_exec_quiet command to execute
  333. # usage: ynh_exec_quiet "command to execute | following command"
  334. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  335. #
  336. # | arg: command - command to execute
  337. ynh_exec_quiet () {
  338. eval $@ > /dev/null
  339. }
  340. # Execute a command and redirect stdout and stderr in /dev/null
  341. #
  342. # usage: ynh_exec_fully_quiet command to execute
  343. # usage: ynh_exec_fully_quiet "command to execute | following command"
  344. # In case of use of pipes, you have to use double quotes. Otherwise, this helper will be executed with the first command, then be send to the next pipe.
  345. #
  346. # | arg: command - command to execute
  347. ynh_exec_fully_quiet () {
  348. eval $@ > /dev/null 2>&1
  349. }
  350. # Remove any logs for all the following commands.
  351. #
  352. # usage: ynh_print_OFF
  353. # WARNING: You should be careful with this helper, and never forgot to use ynh_print_ON as soon as possible to restore the logging.
  354. ynh_print_OFF () {
  355. set +x
  356. }
  357. # Restore the logging after ynh_print_OFF
  358. #
  359. # usage: ynh_print_ON
  360. ynh_print_ON () {
  361. set -x
  362. # Print an echo only for the log, to be able to know that ynh_print_ON has been called.
  363. echo ynh_print_ON > /dev/null
  364. }
  365. #=================================================
  366. # Install or update the main directory yunohost.multimedia
  367. #
  368. # usage: ynh_multimedia_build_main_dir
  369. ynh_multimedia_build_main_dir () {
  370. local ynh_media_release="v1.0"
  371. local checksum="4852c8607db820ad51f348da0dcf0c88"
  372. # Download yunohost.multimedia scripts
  373. wget -nv https://github.com/YunoHost-Apps/yunohost.multimedia/archive/${ynh_media_release}.tar.gz
  374. # Check the control sum
  375. echo "${checksum} ${ynh_media_release}.tar.gz" | md5sum -c --status \
  376. || ynh_die "Corrupt source"
  377. # Extract
  378. mkdir yunohost.multimedia-master
  379. tar -xf ${ynh_media_release}.tar.gz -C yunohost.multimedia-master --strip-components 1
  380. ./yunohost.multimedia-master/script/ynh_media_build.sh
  381. }
  382. # Add a directory in yunohost.multimedia
  383. # This "directory" will be a symbolic link to a existing directory.
  384. #
  385. # usage: ynh_multimedia_addfolder "Source directory" "Destination directory"
  386. #
  387. # | arg: -s, --source_dir= - Source directory - The real directory which contains your medias.
  388. # | arg: -d, --dest_dir= - Destination directory - The name and the place of the symbolic link, relative to "/home/yunohost.multimedia"
  389. ynh_multimedia_addfolder () {
  390. # Declare an array to define the options of this helper.
  391. declare -Ar args_array=( [s]=source_dir= [d]=dest_dir= )
  392. local source_dir
  393. local dest_dir
  394. # Manage arguments with getopts
  395. ynh_handle_getopts_args "$@"
  396. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --source="$source_dir" --dest="$dest_dir"
  397. }
  398. # Move a directory in yunohost.multimedia, and replace by a symbolic link
  399. #
  400. # usage: ynh_multimedia_movefolder "Source directory" "Destination directory"
  401. #
  402. # | arg: -s, --source_dir= - Source directory - The real directory which contains your medias.
  403. # It will be moved to "Destination directory"
  404. # A symbolic link will replace it.
  405. # | arg: -d, --dest_dir= - Destination directory - The new name and place of the directory, relative to "/home/yunohost.multimedia"
  406. ynh_multimedia_movefolder () {
  407. # Declare an array to define the options of this helper.
  408. declare -Ar args_array=( [s]=source_dir= [d]=dest_dir= )
  409. local source_dir
  410. local dest_dir
  411. # Manage arguments with getopts
  412. ynh_handle_getopts_args "$@"
  413. ./yunohost.multimedia-master/script/ynh_media_addfolder.sh --inv --source="$source_dir" --dest="$dest_dir"
  414. }
  415. # Allow an user to have an write authorisation in multimedia directories
  416. #
  417. # usage: ynh_multimedia_addaccess user_name
  418. #
  419. # | arg: -u, --user_name= - The name of the user which gain this access.
  420. ynh_multimedia_addaccess () {
  421. # Declare an array to define the options of this helper.
  422. declare -Ar args_array=( [u]=user_name=)
  423. local user_name
  424. # Manage arguments with getopts
  425. ynh_handle_getopts_args "$@"
  426. groupadd -f multimedia
  427. usermod -a -G multimedia $user_name
  428. }
  429. #=================================================
  430. # Create a dedicated fail2ban config (jail and filter conf files)
  431. #
  432. # usage: ynh_add_fail2ban_config log_file filter [max_retry [ports]]
  433. # | arg: log_file - Log file to be checked by fail2ban
  434. # | arg: failregex - Failregex to be looked for by fail2ban
  435. # | arg: max_retry - Maximum number of retries allowed before banning IP address - default: 3
  436. # | arg: ports - Ports blocked for a banned IP address - default: http,https
  437. ynh_add_fail2ban_config () {
  438. # Process parameters
  439. logpath=$1
  440. failregex=$2
  441. max_retry=${3:-3}
  442. ports=${4:-http,https}
  443. test -n "$logpath" || ynh_die "ynh_add_fail2ban_config expects a logfile path as first argument and received nothing."
  444. test -n "$failregex" || ynh_die "ynh_add_fail2ban_config expects a failure regex as second argument and received nothing."
  445. finalfail2banjailconf="/etc/fail2ban/jail.d/$app.conf"
  446. finalfail2banfilterconf="/etc/fail2ban/filter.d/$app.conf"
  447. ynh_backup_if_checksum_is_different "$finalfail2banjailconf" 1
  448. ynh_backup_if_checksum_is_different "$finalfail2banfilterconf" 1
  449. sudo tee $finalfail2banjailconf <<EOF
  450. [$app]
  451. enabled = true
  452. port = $ports
  453. filter = $app
  454. logpath = $logpath
  455. maxretry = $max_retry
  456. EOF
  457. sudo tee $finalfail2banfilterconf <<EOF
  458. [INCLUDES]
  459. before = common.conf
  460. [Definition]
  461. failregex = $failregex
  462. ignoreregex =
  463. EOF
  464. ynh_store_file_checksum "$finalfail2banjailconf"
  465. ynh_store_file_checksum "$finalfail2banfilterconf"
  466. systemctl reload fail2ban
  467. local fail2ban_error="$(journalctl -u fail2ban | tail -n50 | grep "WARNING.*$app.*")"
  468. if [ -n "$fail2ban_error" ]
  469. then
  470. echo "[ERR] Fail2ban failed to load the jail for $app" >&2
  471. echo "WARNING${fail2ban_error#*WARNING}" >&2
  472. fi
  473. }
  474. # Remove the dedicated fail2ban config (jail and filter conf files)
  475. #
  476. # usage: ynh_remove_fail2ban_config
  477. ynh_remove_fail2ban_config () {
  478. ynh_secure_remove "/etc/fail2ban/jail.d/$app.conf"
  479. ynh_secure_remove "/etc/fail2ban/filter.d/$app.conf"
  480. systemctl reload fail2ban
  481. }
  482. #=================================================
  483. # Read the value of a key in a ynh manifest file
  484. #
  485. # usage: ynh_read_manifest manifest key
  486. # | arg: manifest - Path of the manifest to read
  487. # | arg: key - Name of the key to find
  488. ynh_read_manifest () {
  489. manifest="$1"
  490. key="$2"
  491. python3 -c "import sys, json;print(json.load(open('$manifest', encoding='utf-8'))['$key'])"
  492. }
  493. # Read the upstream version from the manifest
  494. # The version number in the manifest is defined by <upstreamversion>~ynh<packageversion>
  495. # For example : 4.3-2~ynh3
  496. # This include the number before ~ynh
  497. # In the last example it return 4.3-2
  498. #
  499. # usage: ynh_app_upstream_version
  500. ynh_app_upstream_version () {
  501. manifest_path="../manifest.json"
  502. if [ ! -e "$manifest_path" ]; then
  503. manifest_path="../settings/manifest.json" # Into the restore script, the manifest is not at the same place
  504. fi
  505. version_key=$(ynh_read_manifest "$manifest_path" "version")
  506. echo "${version_key/~ynh*/}"
  507. }
  508. # Read package version from the manifest
  509. # The version number in the manifest is defined by <upstreamversion>~ynh<packageversion>
  510. # For example : 4.3-2~ynh3
  511. # This include the number after ~ynh
  512. # In the last example it return 3
  513. #
  514. # usage: ynh_app_package_version
  515. ynh_app_package_version () {
  516. manifest_path="../manifest.json"
  517. if [ ! -e "$manifest_path" ]; then
  518. manifest_path="../settings/manifest.json" # Into the restore script, the manifest is not at the same place
  519. fi
  520. version_key=$(ynh_read_manifest "$manifest_path" "version")
  521. echo "${version_key/*~ynh/}"
  522. }
  523. # Checks the app version to upgrade with the existing app version and returns:
  524. # - UPGRADE_APP if the upstream app version has changed
  525. # - UPGRADE_PACKAGE if only the YunoHost package has changed
  526. #
  527. ## It stops the current script without error if the package is up-to-date
  528. #
  529. # This helper should be used to avoid an upgrade of an app, or the upstream part
  530. # of it, when it's not needed
  531. #
  532. # To force an upgrade, even if the package is up to date,
  533. # you have to set the variable YNH_FORCE_UPGRADE before.
  534. # example: sudo YNH_FORCE_UPGRADE=1 yunohost app upgrade MyApp
  535. # usage: ynh_check_app_version_changed
  536. ynh_check_app_version_changed () {
  537. local force_upgrade=${YNH_FORCE_UPGRADE:-0}
  538. local package_check=${PACKAGE_CHECK_EXEC:-0}
  539. # By default, upstream app version has changed
  540. local return_value="UPGRADE_APP"
  541. local current_version=$(ynh_read_manifest "/etc/yunohost/apps/$YNH_APP_INSTANCE_NAME/manifest.json" "version" || echo 1.0)
  542. local current_upstream_version="${current_version/~ynh*/}"
  543. local update_version=$(ynh_read_manifest "../manifest.json" "version" || echo 1.0)
  544. local update_upstream_version="${update_version/~ynh*/}"
  545. if [ "$current_version" == "$update_version" ] ; then
  546. # Complete versions are the same
  547. if [ "$force_upgrade" != "0" ]
  548. then
  549. echo "Upgrade forced by YNH_FORCE_UPGRADE." >&2
  550. unset YNH_FORCE_UPGRADE
  551. elif [ "$package_check" != "0" ]
  552. then
  553. echo "Upgrade forced for package check." >&2
  554. else
  555. ynh_die "Up-to-date, nothing to do" 0
  556. fi
  557. elif [ "$current_upstream_version" == "$update_upstream_version" ] ; then
  558. # Upstream versions are the same, only YunoHost package versions differ
  559. return_value="UPGRADE_PACKAGE"
  560. fi
  561. echo $return_value
  562. }
  563. #=================================================
  564. # Send an email to inform the administrator
  565. #
  566. # usage: ynh_send_readme_to_admin app_message [recipients]
  567. # | arg: -m --app_message= - The message to send to the administrator.
  568. # | arg: -r, --recipients= - The recipients of this email. Use spaces to separate multiples recipients. - default: root
  569. # example: "root admin@domain"
  570. # If you give the name of a YunoHost user, ynh_send_readme_to_admin will find its email adress for you
  571. # example: "root admin@domain user1 user2"
  572. ynh_send_readme_to_admin() {
  573. # Declare an array to define the options of this helper.
  574. declare -Ar args_array=( [m]=app_message= [r]=recipients= )
  575. local app_message
  576. local recipients
  577. # Manage arguments with getopts
  578. ynh_handle_getopts_args "$@"
  579. local app_message="${app_message:-...No specific information...}"
  580. local recipients="${recipients:-root}"
  581. # Retrieve the email of users
  582. find_mails () {
  583. local list_mails="$1"
  584. local mail
  585. local recipients=" "
  586. # Read each mail in argument
  587. for mail in $list_mails
  588. do
  589. # Keep root or a real email address as it is
  590. if [ "$mail" = "root" ] || echo "$mail" | grep --quiet "@"
  591. then
  592. recipients="$recipients $mail"
  593. else
  594. # But replace an user name without a domain after by its email
  595. if mail=$(ynh_user_get_info "$mail" "mail" 2> /dev/null)
  596. then
  597. recipients="$recipients $mail"
  598. fi
  599. fi
  600. done
  601. echo "$recipients"
  602. }
  603. recipients=$(find_mails "$recipients")
  604. local mail_subject="☁️🆈🅽🅷☁️: \`$app\` was just installed!"
  605. local mail_message="This is an automated message from your beloved YunoHost server.
  606. Specific information for the application $app.
  607. $app_message
  608. ---
  609. Automatic diagnosis data from YunoHost
  610. $(yunohost tools diagnosis | grep -B 100 "services:" | sed '/services:/d')"
  611. # Define binary to use for mail command
  612. if [ -e /usr/bin/bsd-mailx ]
  613. then
  614. local mail_bin=/usr/bin/bsd-mailx
  615. else
  616. local mail_bin=/usr/bin/mail.mailutils
  617. fi
  618. # Send the email to the recipients
  619. echo "$mail_message" | $mail_bin -a "Content-Type: text/plain; charset=UTF-8" -s "$mail_subject" "$recipients"
  620. }
  621. #=================================================
  622. # Reload (or other actions) a service and print a log in case of failure.
  623. #
  624. # usage: ynh_system_reload service_name [action]
  625. # | arg: -n, --service_name= - Name of the service to reload
  626. # | arg: -a, --action= - Action to perform with systemctl. Default: reload
  627. ynh_system_reload () {
  628. # Declare an array to define the options of this helper.
  629. declare -Ar args_array=( [n]=service_name= [a]=action= )
  630. local service_name
  631. local action
  632. # Manage arguments with getopts
  633. ynh_handle_getopts_args "$@"
  634. local action=${action:-reload}
  635. # Reload, restart or start and print the log if the service fail to start or reload
  636. systemctl $action $service_name || ( journalctl --lines=20 -u $service_name >&2 && false)
  637. }
  638. #=================================================
  639. ynh_debian_release () {
  640. lsb_release --codename --short
  641. }
  642. is_stretch () {
  643. if [ "$(ynh_debian_release)" == "stretch" ]
  644. then
  645. return 0
  646. else
  647. return 1
  648. fi
  649. }
  650. is_jessie () {
  651. if [ "$(ynh_debian_release)" == "jessie" ]
  652. then
  653. return 0
  654. else
  655. return 1
  656. fi
  657. }
  658. #=================================================
  659. # Delete a file checksum from the app settings
  660. #
  661. # $app should be defined when calling this helper
  662. #
  663. # usage: ynh_remove_file_checksum file
  664. # | arg: file - The file for which the checksum will be deleted
  665. ynh_delete_file_checksum () {
  666. local checksum_setting_name=checksum_${1//[\/ ]/_} # Replace all '/' and ' ' by '_'
  667. ynh_app_setting_delete $app $checksum_setting_name
  668. }
  669. #=================================================
  670. ynh_maintenance_mode_ON () {
  671. # Load value of $path_url and $domain from the config if their not set
  672. if [ -z $path_url ]; then
  673. path_url=$(ynh_app_setting_get $app path)
  674. fi
  675. if [ -z $domain ]; then
  676. domain=$(ynh_app_setting_get $app domain)
  677. fi
  678. # Create an html to serve as maintenance notice
  679. echo "<!DOCTYPE html>
  680. <html>
  681. <head>
  682. <meta http-equiv="refresh" content="3">
  683. <title>Your app $app is currently under maintenance!</title>
  684. <style>
  685. body {
  686. width: 70em;
  687. margin: 0 auto;
  688. }
  689. </style>
  690. </head>
  691. <body>
  692. <h1>Your app $app is currently under maintenance!</h1>
  693. <p>This app has been put under maintenance by your administrator at $(date)</p>
  694. <p>Please wait until the maintenance operation is done. This page will be reloaded as soon as your app will be back.</p>
  695. </body>
  696. </html>" > "/var/www/html/maintenance.$app.html"
  697. # Create a new nginx config file to redirect all access to the app to the maintenance notice instead.
  698. echo "# All request to the app will be redirected to ${path_url}_maintenance and fall on the maintenance notice
  699. rewrite ^${path_url}/(.*)$ ${path_url}_maintenance/? redirect;
  700. # Use another location, to not be in conflict with the original config file
  701. location ${path_url}_maintenance/ {
  702. alias /var/www/html/ ;
  703. try_files maintenance.$app.html =503;
  704. # Include SSOWAT user panel.
  705. include conf.d/yunohost_panel.conf.inc;
  706. }" > "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  707. # The current config file will redirect all requests to the root of the app.
  708. # To keep the full path, we can use the following rewrite rule:
  709. # rewrite ^${path_url}/(.*)$ ${path_url}_maintenance/\$1? redirect;
  710. # The difference will be in the $1 at the end, which keep the following queries.
  711. # But, if it works perfectly for a html request, there's an issue with any php files.
  712. # This files are treated as simple files, and will be downloaded by the browser.
  713. # Would be really be nice to be able to fix that issue. So that, when the page is reloaded after the maintenance, the user will be redirected to the real page he was.
  714. systemctl reload nginx
  715. }
  716. ynh_maintenance_mode_OFF () {
  717. # Load value of $path_url and $domain from the config if their not set
  718. if [ -z $path_url ]; then
  719. path_url=$(ynh_app_setting_get $app path)
  720. fi
  721. if [ -z $domain ]; then
  722. domain=$(ynh_app_setting_get $app domain)
  723. fi
  724. # Rewrite the nginx config file to redirect from ${path_url}_maintenance to the real url of the app.
  725. echo "rewrite ^${path_url}_maintenance/(.*)$ ${path_url}/\$1 redirect;" > "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  726. systemctl reload nginx
  727. # Sleep 4 seconds to let the browser reload the pages and redirect the user to the app.
  728. sleep 4
  729. # Then remove the temporary files used for the maintenance.
  730. rm "/var/www/html/maintenance.$app.html"
  731. rm "/etc/nginx/conf.d/$domain.d/maintenance.$app.conf"
  732. systemctl reload nginx
  733. }