common.sh 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 "Missing derivation parameter, this is unsafe, 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. logs_folder="${ROOT_FOLDER}/logs"
  47. if [ "$(find "${logs_folder}" -maxdepth 1 -type f | wc -l)" -gt 0 ]; then
  48. echo "Cleaning logs folder..."
  49. files=($(ls -d "${logs_folder}"/* | xargs -n 1 basename | sed 's/\///g'))
  50. for file in "${files[@]}"; do
  51. echo "Removing ${file}"
  52. rm -rf "${ROOT_FOLDER}/logs/${file}"
  53. done
  54. fi
  55. }
  56. function kill_watcher() {
  57. watcher_pid="$(ps aux | grep "scripts/watcher" | grep -v grep | awk '{print $2}')"
  58. # kill it if it's running
  59. if [[ -n $watcher_pid ]]; then
  60. # If multiline kill each pid
  61. if [[ $watcher_pid == *" "* ]]; then
  62. for pid in $watcher_pid; do
  63. kill -9 $pid
  64. done
  65. else
  66. kill -9 $watcher_pid
  67. fi
  68. fi
  69. }