common.sh 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/env bash
  2. # Get field from json file
  3. function get_json_field() {
  4. local json_file="$1"
  5. local field="$2"
  6. jq -r ".${field}" "${json_file}"
  7. }
  8. function write_log() {
  9. local message="$1"
  10. local log_file="${PWD}/logs/script.log"
  11. echo "$(date) - ${message}" >>"${log_file}"
  12. }
  13. function derive_entropy() {
  14. SEED_FILE="${STATE_FOLDER}/seed"
  15. identifier="${1}"
  16. tipi_seed=$(cat "${SEED_FILE}") || true
  17. if [[ -z "$tipi_seed" ]] || [[ -z "$identifier" ]]; then
  18. echo >&2 "Seed file not found. exiting..."
  19. exit 1
  20. fi
  21. printf "%s" "${identifier}" | openssl dgst -sha256 -hmac "${tipi_seed}" | sed 's/^.* //'
  22. }
  23. function ensure_pwd() {
  24. if [[ $(basename "$(pwd)") != "runtipi" ]] || [[ ! -f "${BASH_SOURCE[0]}" ]]; then
  25. echo "Please run this script from the runtipi directory"
  26. exit 1
  27. fi
  28. }
  29. function ensure_root() {
  30. if [[ $UID != 0 ]]; then
  31. echo "Tipi must be started as root"
  32. echo "Please re-run this script as"
  33. echo " sudo ./scripts/start"
  34. exit 1
  35. fi
  36. }
  37. function ensure_linux() {
  38. # Check we are on linux
  39. if [[ "$(uname)" != "Linux" ]]; then
  40. echo "Tipi only works on Linux"
  41. exit 1
  42. fi
  43. }
  44. function clean_logs() {
  45. # Clean logs folder
  46. local logs_folder="${ROOT_FOLDER}/logs"
  47. # Create the folder if it doesn't exist
  48. if [[ ! -d "${logs_folder}" ]]; then
  49. mkdir "${logs_folder}"
  50. fi
  51. if [ "$(find "${logs_folder}" -maxdepth 1 -type f | wc -l)" -gt 0 ]; then
  52. echo "Cleaning logs folder..."
  53. local files=($(ls -d "${logs_folder}"/* | xargs -n 1 basename | sed 's/\///g'))
  54. for file in "${files[@]}"; do
  55. echo "Removing ${file}"
  56. rm -rf "${ROOT_FOLDER}/logs/${file}"
  57. done
  58. fi
  59. }
  60. function kill_watcher() {
  61. local watcher_pid="$(ps aux | grep "scripts/watcher" | grep -v grep | awk '{print $2}')"
  62. # kill it if it's running
  63. if [[ -n $watcher_pid ]]; then
  64. # If multiline kill each pid
  65. if [[ $watcher_pid == *" "* ]]; then
  66. for pid in $watcher_pid; do
  67. # shellcheck disable=SC2086
  68. kill -9 $pid
  69. done
  70. else
  71. # shellcheck disable=SC2086
  72. kill -9 $watcher_pid
  73. fi
  74. fi
  75. }