lib.sh 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. #!/usr/bin/env bash
  2. # -*- coding: utf-8; mode: sh indent-tabs-mode: nil -*-
  3. # shellcheck disable=SC2059,SC1117,SC2162,SC2004
  4. ADMIN_NAME="${ADMIN_NAME:-$(git config user.name)}"
  5. ADMIN_NAME="${ADMIN_NAME:-$USER}"
  6. ADMIN_EMAIL="${ADMIN_EMAIL:-$(git config user.email)}"
  7. ADMIN_EMAIL="${ADMIN_EMAIL:-$USER@$(hostname)}"
  8. if [[ -z "${REPO_ROOT}" ]]; then
  9. REPO_ROOT=$(dirname "${BASH_SOURCE[0]}")
  10. while [ -h "${REPO_ROOT}" ] ; do
  11. REPO_ROOT=$(readlink "${REPO_ROOT}")
  12. done
  13. REPO_ROOT=$(cd "${REPO_ROOT}/.." && pwd -P )
  14. fi
  15. if [[ -z ${TEMPLATES} ]]; then
  16. TEMPLATES="${REPO_ROOT}/utils/templates"
  17. fi
  18. if [[ -z "$CACHE" ]]; then
  19. CACHE="${REPO_ROOT}/cache"
  20. fi
  21. if [[ -z "$SYSTEMD_UNITS" ]]; then
  22. SYSTEMD_UNITS="/lib/systemd/system"
  23. fi
  24. if [[ -z ${DIFF_CMD} ]]; then
  25. DIFF_CMD="diff -u"
  26. if command -v colordiff >/dev/null; then
  27. DIFF_CMD="colordiff -u"
  28. fi
  29. fi
  30. sudo_or_exit() {
  31. # usage: sudo_or_exit
  32. if [ ! "$(id -u)" -eq 0 ]; then
  33. err_msg "this command requires root (sudo) privilege!" >&2
  34. exit 42
  35. fi
  36. }
  37. rst_title() {
  38. # usage: rst_title <header-text> [part|chapter|section]
  39. case ${2-chapter} in
  40. part) printf "\n${1//?/=}\n$1\n${1//?/=}\n";;
  41. chapter) printf "\n${1}\n${1//?/=}\n";;
  42. section) printf "\n${1}\n${1//?/-}\n";;
  43. *)
  44. err_msg "invalid argument '${2}' in line $(caller)"
  45. return 42
  46. ;;
  47. esac
  48. }
  49. if command -v fmt >/dev/null; then
  50. export FMT="fmt -u"
  51. else
  52. export FMT="cat"
  53. fi
  54. rst_para() {
  55. # usage: RST_INDENT=1 rst_para "lorem ipsum ..."
  56. local prefix=''
  57. if ! [[ -z $RST_INDENT ]] && [[ $RST_INDENT -gt 0 ]]; then
  58. prefix="$(for i in $(seq 1 "$RST_INDENT"); do printf " "; done)"
  59. echo -en "\n$*\n" | $FMT | prefix_stdout "$prefix"
  60. else
  61. echo -en "\n$*\n" | $FMT
  62. fi
  63. }
  64. err_msg() { echo -e "ERROR: $*" >&2; }
  65. warn_msg() { echo -e "WARN: $*" >&2; }
  66. info_msg() { echo -e "INFO: $*"; }
  67. clean_stdin() {
  68. if [[ $(uname -s) != 'Darwin' ]]; then
  69. while read -n1 -t 0.1; do : ; done
  70. fi
  71. }
  72. wait_key(){
  73. # usage: waitKEY [<timeout in sec>]
  74. clean_stdin
  75. local _t=$1
  76. [[ ! -z $FORCE_TIMEOUT ]] && _t=$FORCE_TIMEOUT
  77. [[ ! -z $_t ]] && _t="-t $_t"
  78. # shellcheck disable=SC2086
  79. read -s -n1 $_t -p "** press any [KEY] to continue **"
  80. echo
  81. clean_stdin
  82. }
  83. ask_yn() {
  84. # usage: ask_yn <prompt-text> [Ny|Yn] [<timeout in sec>]
  85. local EXIT_YES=0 # exit status 0 --> successful
  86. local EXIT_NO=1 # exit status 1 --> error code
  87. local _t=$3
  88. [[ ! -z $FORCE_TIMEOUT ]] && _t=$FORCE_TIMEOUT
  89. [[ ! -z $_t ]] && _t="-t $_t"
  90. case "${2}" in
  91. Yn)
  92. local exit_val=${EXIT_YES}
  93. local choice="[YES/no]"
  94. local default="Yes"
  95. ;;
  96. *)
  97. local exit_val=${EXIT_NO}
  98. local choice="[NO/yes]"
  99. local default="No"
  100. ;;
  101. esac
  102. echo
  103. while true; do
  104. clean_stdin
  105. printf "$1 ${choice} "
  106. # shellcheck disable=SC2086
  107. read -n1 $_t
  108. if [[ -z $REPLY ]]; then
  109. printf "$default\n"; break
  110. elif [[ $REPLY =~ ^[Yy]$ ]]; then
  111. exit_val=${EXIT_YES}
  112. printf "\n"
  113. break
  114. elif [[ $REPLY =~ ^[Nn]$ ]]; then
  115. exit_val=${EXIT_NO}
  116. printf "\n"
  117. break
  118. fi
  119. _t=""
  120. err_msg "invalid choice"
  121. done
  122. clean_stdin
  123. return $exit_val
  124. }
  125. tee_stderr () {
  126. # usage::
  127. # tee_stderr 1 <<EOF | python -i
  128. # print("hello")
  129. # EOF
  130. # ...
  131. # >>> print("hello")
  132. # hello
  133. local _t="0";
  134. if [[ ! -z $1 ]] ; then _t="$1"; fi
  135. (while read line; do
  136. # shellcheck disable=SC2086
  137. sleep $_t
  138. echo -e "$line" >&2
  139. echo "$line"
  140. done)
  141. }
  142. prefix_stdout () {
  143. # usage: <cmd> | prefix_stdout [prefix]
  144. local prefix=" | "
  145. if [[ ! -z $1 ]] ; then prefix="$1"; fi
  146. (while IFS= read line; do
  147. echo -e "${prefix}$line"
  148. done)
  149. }
  150. append_line() {
  151. # usage: append_line <line> <file>
  152. #
  153. # Append line if not exists, create file if not exists. E.g::
  154. #
  155. # append_line 'source ~/.foo' ~/bashrc
  156. local LINE=$1
  157. local FILE=$2
  158. grep -qFs -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
  159. }
  160. cache_download() {
  161. # usage: cache_download <url> <local-filename>
  162. local exit_value=0
  163. if [[ ! -z ${SUDO_USER} ]]; then
  164. sudo -u "${SUDO_USER}" mkdir -p "${CACHE}"
  165. else
  166. mkdir -p "${CACHE}"
  167. fi
  168. if [[ -f "${CACHE}/$2" ]] ; then
  169. info_msg "already cached: $1"
  170. info_msg " --> ${CACHE}/$2"
  171. fi
  172. if [[ ! -f "${CACHE}/$2" ]]; then
  173. info_msg "caching: $1"
  174. info_msg " --> ${CACHE}/$2"
  175. if [[ ! -z ${SUDO_USER} ]]; then
  176. sudo -u "${SUDO_USER}" wget --progress=bar -O "${CACHE}/$2" "$1" ; exit_value=$?
  177. else
  178. wget --progress=bar -O "${CACHE}/$2" "$1" ; exit_value=$?
  179. fi
  180. if $exit_value; then
  181. err_msg "failed to download: $1"
  182. fi
  183. fi
  184. }
  185. choose_one() {
  186. # usage:
  187. #
  188. # DEFAULT_SELECT= 2 \
  189. # choose_one <name> "your selection?" "Coffee" "Coffee with milk"
  190. local default=${DEFAULT_SELECT-1}
  191. local REPLY
  192. local env_name=$1 && shift
  193. local choice=$1;
  194. local max="${#@}"
  195. local _t
  196. [[ ! -z $FORCE_TIMEOUT ]] && _t=$FORCE_TIMEOUT
  197. [[ ! -z $_t ]] && _t="-t $_t"
  198. list=("$@")
  199. echo -e "Menu::"
  200. for ((i=1; i<= $(($max -1)); i++)); do
  201. if [[ "$i" == "$default" ]]; then
  202. echo -e " $i.) ${list[$i]} [default]"
  203. else
  204. echo -e " $i.) ${list[$i]}"
  205. fi
  206. done
  207. while true; do
  208. clean_stdin
  209. printf "$1 [$default] "
  210. if (( 10 > $max )); then
  211. # shellcheck disable=SC2086
  212. read -n1 $_t
  213. else
  214. # shellcheck disable=SC2086,SC2229
  215. read $_t
  216. fi
  217. # selection fits
  218. [[ $REPLY =~ ^-?[0-9]+$ ]] && (( $REPLY > 0 )) && (( $REPLY < $max )) && break
  219. # take default
  220. [[ -z $REPLY ]] && REPLY=$default && break
  221. _t=""
  222. err_msg "invalid choice"
  223. done
  224. eval "$env_name"='${list[${REPLY}]}'
  225. echo
  226. clean_stdin
  227. }
  228. install_template() {
  229. # usage:
  230. #
  231. # install_template [--no-eval] [--variant=<name>] \
  232. # {file} [{owner} [{group} [{chmod}]]]
  233. #
  234. # E.g. the origin of variant 'raw' of /etc/updatedb.conf is::
  235. #
  236. # ${TEMPLATES}/etc/updatedb.conf:raw
  237. #
  238. # To install variant 'raw' of /etc/updatedb.conf without evaluated
  239. # replacements you can use::
  240. #
  241. # install_template --variant=raw --no-eval \
  242. # /etc/updatedb.conf root root 644
  243. local _reply=""
  244. local do_eval=1
  245. local variant=""
  246. local pos_args=("$0")
  247. for i in "$@"; do
  248. case $i in
  249. --no-eval) do_eval=0; shift ;;
  250. --variant=*) variant=":${i#*=}"; shift ;;
  251. *) pos_args+=("$i") ;;
  252. esac
  253. done
  254. local dst="${pos_args[1]}"
  255. local template_origin="${TEMPLATES}${dst}${variant}"
  256. local template_file="${TEMPLATES}${dst}"
  257. local owner="${pos_args[2]-$(id -un)}"
  258. local group="${pos_args[3]-$(id -gn)}"
  259. local chmod="${pos_args[4]-644}"
  260. info_msg "install (eval=$do_eval): ${dst}"
  261. [[ ! -z $variant ]] && info_msg "variant: ${variant}"
  262. if [[ ! -f "${template_origin}" ]] ; then
  263. err_msg "${template_origin} does not exists"
  264. err_msg "... can't install $dst"
  265. wait_key 30
  266. return 42
  267. fi
  268. if [[ "$do_eval" == "1" ]]; then
  269. template_file="${CACHE}${dst}${variant}"
  270. info_msg "BUILD template ${template_file}"
  271. if [[ ! -z ${SUDO_USER} ]]; then
  272. sudo -u "${SUDO_USER}" mkdir -p "$(dirname "${template_file}")"
  273. else
  274. mkdir -p "$(dirname "${template_file}")"
  275. fi
  276. # shellcheck disable=SC2086
  277. eval "echo \"$(cat ${template_origin})\"" > "${template_file}"
  278. if [[ ! -z ${SUDO_USER} ]]; then
  279. chown "${SUDO_USER}:${SUDO_USER}" "${template_file}"
  280. fi
  281. else
  282. template_file=$template_origin
  283. fi
  284. mkdir -p "$(dirname "${dst}")"
  285. if [[ ! -f "${dst}" ]]; then
  286. info_msg "install: ${template_file}"
  287. sudo -H install -v -o "${owner}" -g "${group}" -m "${chmod}" \
  288. "${template_file}" "${dst}" | prefix_stdout
  289. return $?
  290. fi
  291. if [[ -f "${dst}" ]] && cmp --silent "${template_file}" "${dst}" ; then
  292. info_msg "file ${dst} allready installed"
  293. return 0
  294. fi
  295. info_msg "diffrent file ${dst} allready exists on this host"
  296. while true; do
  297. choose_one _reply "choose next step with file $dst" \
  298. "replace file" \
  299. "leave file unchanged" \
  300. "interactiv shell" \
  301. "diff files"
  302. case $_reply in
  303. "replace file")
  304. info_msg "install: ${template_file}"
  305. sudo -H install -v -o "${owner}" -g "${group}" -m "${chmod}" \
  306. "${template_file}" "${dst}" | prefix_stdout
  307. break
  308. ;;
  309. "leave file unchanged")
  310. break
  311. ;;
  312. "interactiv shell")
  313. echo "// edit ${dst} to your needs"
  314. echo "// exit with CTRL-D"
  315. sudo -H -u "${owner}" -i
  316. $DIFF_CMD "${dst}" "${template_file}"
  317. echo
  318. echo "did you edit file ..."
  319. printf " ${template_file}"
  320. if ask_yn "... to your needs?"; then
  321. break
  322. fi
  323. ;;
  324. "diff files")
  325. $DIFF_CMD "${dst}" "${template_file}" | prefix_stdout
  326. esac
  327. done
  328. }
  329. # Apache
  330. # ------
  331. # FIXME: Arch Linux & RHEL should be added
  332. if [[ -z "${APACHE_SITES_AVAILABE}" ]]; then
  333. APACHE_SITES_AVAILABE="/etc/apache2/sites-available"
  334. fi
  335. apache_is_installed() {
  336. (command -v apachectl \
  337. && command -v a2ensite \
  338. && command -v a2dissite ) &>/dev/null
  339. }
  340. apache_reload() {
  341. info_msg "reload apache .."
  342. echo
  343. sudo -H apachectl configtest
  344. sudo -H service apache2 force-reload
  345. }
  346. apache_install_site() {
  347. # usage: apache_install_site [<template option> ...] <mysite.conf>
  348. #
  349. # <template option>: see install_template
  350. local template_opts=()
  351. local pos_args=("$0")
  352. for i in "$@"; do
  353. case $i in
  354. -*) template_opts+=("$i");;
  355. *) pos_args+=("$i");;
  356. esac
  357. done
  358. install_template "${template_opts[@]}" \
  359. "${APACHE_SITES_AVAILABE}/${pos_args[1]}" \
  360. root root 644
  361. apache_enable_site "${pos_args[1]}"
  362. apache_reload
  363. info_msg "installed apache site: ${pos_args[1]}"
  364. }
  365. apache_enable_site() {
  366. info_msg "enable apache site $1 .."
  367. sudo -H a2ensite -q "$1"
  368. apache_reload
  369. }
  370. apache_dissable_site() {
  371. info_msg "disable apache site $1 .."
  372. sudo -H a2dissite -q "$1"
  373. apache_reload
  374. }
  375. # uWSGI
  376. # -----
  377. uWSGI_SETUP="${uWSGI_SETUP:=/etc/uwsgi}"
  378. uWSGI_restart() {
  379. # usage: uWSGI_restart()
  380. info_msg "restart uWSGI service"
  381. sudo -H systemctl restart uwsgi
  382. }
  383. uWSGI_app_available() {
  384. # usage: uWSGI_app_available <myapp.ini>
  385. local CONF="$1"
  386. if [[ -z $CONF ]]; then
  387. err_msg "uWSGI_app_available: missing arguments"
  388. return 42
  389. fi
  390. [[ -f "${uWSGI_SETUP}/apps-available/${CONF}" ]]
  391. }
  392. uWSGI_install_app() {
  393. # usage: uWSGI_install_app [<template option> ...] <myapp.ini>
  394. #
  395. # <template option>: see install_template
  396. local pos_args=("$0")
  397. for i in "$@"; do
  398. case $i in
  399. -*) template_opts+=("$i");;
  400. *) pos_args+=("$i");;
  401. esac
  402. done
  403. install_template "${template_opts[@]}" \
  404. "${uWSGI_SETUP}/apps-available/${pos_args[1]}" \
  405. root root 644
  406. uWSGI_enable_app "${pos_args[1]}"
  407. uWSGI_restart
  408. info_msg "installed uWSGI app: ${pos_args[1]}"
  409. }
  410. uWSGI_remove_app() {
  411. # usage: uWSGI_remove_app <myapp.ini>
  412. local CONF="$1"
  413. uWSGI_disable_app "${CONF}"
  414. uWSGI_restart
  415. rm -f "${uWSGI_SETUP}/apps-available/${CONF}"
  416. info_msg "removed uWSGI app: ${CONF}"
  417. }
  418. uWSGI_app_enabled() {
  419. # usage: uWSGI_app_enabled <myapp.ini>
  420. local CONF="$1"
  421. if [[ -z $CONF ]]; then
  422. err_msg "uWSGI_app_enabled: missing arguments"
  423. return 42
  424. fi
  425. [[ -f "${uWSGI_SETUP}/apps-enabled/${CONF}" ]]
  426. }
  427. # shellcheck disable=SC2164
  428. uWSGI_enable_app() {
  429. # usage: uWSGI_enable_app <myapp.ini>
  430. local CONF="$1"
  431. if [[ -z $CONF ]]; then
  432. err_msg "uWSGI_enable_app: missing arguments"
  433. return 42
  434. fi
  435. pushd "${uWSGI_SETUP}/apps-enabled" >/dev/null
  436. rm -f "$CONF"
  437. # shellcheck disable=SC2226
  438. ln -s "../apps-available/${CONF}"
  439. info_msg "enabled uWSGI app: ${CONF} (restart uWSGI required)"
  440. popd >/dev/null
  441. }
  442. uWSGI_disable_app() {
  443. # usage: uWSGI_disable_app <myapp.ini>
  444. local CONF="$1"
  445. if [[ -z $CONF ]]; then
  446. err_msg "uWSGI_enable_app: missing arguments"
  447. return 42
  448. fi
  449. rm -f "${uWSGI_SETUP}/apps-enabled/${CONF}"
  450. info_msg "disabled uWSGI app: ${CONF} (restart uWSGI required)"
  451. }
  452. # distro's package manager
  453. # ------------------------
  454. #
  455. # FIXME: Arch Linux & RHEL should be added
  456. #
  457. pkg_install() {
  458. # usage: TITEL='install foobar' pkg_install foopkg barpkg
  459. rst_title "${TITLE:-installation of packages}" section
  460. echo -en "\npackage(s)::\n\n $*\n" | $FMT
  461. if ! ask_yn "Should packages be installed?" Yn 30; then
  462. return 42
  463. fi
  464. # shellcheck disable=SC2068
  465. apt-get install -y $@
  466. }
  467. pkg_remove() {
  468. # usage: TITEL='remove foobar' pkg_remove foopkg barpkg
  469. rst_title "${TITLE:-remove packages}" section
  470. echo -en "\npackage(s)::\n\n $*\n" | $FMT
  471. if ! ask_yn "Should packages be removed (purge)?" Yn 30; then
  472. return 42
  473. fi
  474. apt-get purge --autoremove --ignore-missing -y "$@"
  475. }
  476. pkg_is_installed() {
  477. # usage: pkg_is_install foopkg || pkg_install foopkg
  478. dpkg -l "$1" &> /dev/null
  479. return $?
  480. }
  481. # git tooling
  482. # -----------
  483. # shellcheck disable=SC2164
  484. git_clone() {
  485. # usage:
  486. #
  487. # git_clone <url> <name> [<branch> [<user>]]
  488. # git_clone <url> <path> [<branch> [<user>]]
  489. #
  490. # First form uses $CACHE/<name> as destination folder, second form clones
  491. # into <path>. If repository is allready cloned, pull from <branch> and
  492. # update working tree (if needed, the caller has to stash local changes).
  493. #
  494. # git clone https://github.com/asciimoo/searx searx-src origin/master searxlogin
  495. #
  496. local url="$1"
  497. local dest="$2"
  498. local branch="$3"
  499. local user="$4"
  500. local bash_cmd="bash"
  501. local remote="origin"
  502. if [[ ! "${dest:0:1}" = "/" ]]; then
  503. dest="$CACHE/$dest"
  504. fi
  505. [[ -z $branch ]] && branch=master
  506. [[ -z $user ]] && [[ ! -z "${SUDO_USER}" ]] && user="${SUDO_USER}"
  507. [[ ! -z $user ]] && bash_cmd="sudo -H -u $user -i"
  508. if [[ -d "${dest}" ]] ; then
  509. info_msg "already cloned: $dest"
  510. tee_stderr 0.1 <<EOF | $bash_cmd 2>&1 | prefix_stdout " |$user| "
  511. cd "${dest}"
  512. git checkout -m -B "$branch" --track "$remote/$branch"
  513. git pull --all
  514. EOF
  515. else
  516. info_msg "clone into: $dest"
  517. tee_stderr 0.1 <<EOF | $bash_cmd 2>&1 | prefix_stdout " |$user| "
  518. mkdir -p "$(dirname "$dest")"
  519. cd "$(dirname "$dest")"
  520. git clone --branch "$branch" --origin "$remote" "$url" "$(basename "$dest")"
  521. EOF
  522. fi
  523. }