2
0

_common.sh 29 KB

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