rshare 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/bin/sh
  2. PORT=8080
  3. CONFIG=$HOME/.config/rsync/rsync.conf
  4. CACHE_DIR=$HOME/.cache/rsyncd
  5. OPT_HTTP=false
  6. IP=$(ip addr | awk '/state UP/ {getline; getline; $0=$2; gsub(/\/.*/, "");print; exit}')
  7. usage () {
  8. cat <<EOF>&2
  9. Usage: ${0##*/} PATH
  10. Share PATH over the network.
  11. By default, startup an rsync daemon and share PATH as read-only under the
  12. 'files' module. Clients can sync with, for instance:
  13. rsync -iavzzP rsync://$IP:$PORT/files DESTINATION
  14. An HTTP server can be started instead.
  15. Options:
  16. -p PORT: Specify a port number (default: $PORT).
  17. Must be above 1024 to run without privileges.
  18. -H: Start an HTTP server instead.
  19. EOF
  20. }
  21. while getopts ":hHp:" opt; do
  22. case $opt in
  23. h)
  24. usage
  25. exit ;;
  26. H)
  27. OPT_HTTP=true ;;
  28. p)
  29. PORT="$OPTARG" ;;
  30. \?)
  31. usage
  32. exit 1 ;;
  33. esac
  34. done
  35. shift $(($OPTIND - 1))
  36. [ $# -ne 1 ] && usage && exit 1
  37. [ "$1" = "-h" ] && usage && exit
  38. [ "$1" = "--" ] && shift
  39. TARGET=$(realpath "$1")
  40. share_rsync(){
  41. mkdir -p "$(dirname "$CONFIG")" "$CACHE_DIR"
  42. cat<<EOF>"$CONFIG"
  43. pid file = $CACHE_DIR/rsyncd.pid
  44. lock file = $CACHE_DIR/rsyncd.lock
  45. log file = $CACHE_DIR/rsyncd.log
  46. port = $PORT
  47. use chroot = false
  48. [files]
  49. path = $TARGET
  50. comment = Rsync share
  51. read only = true
  52. timeout = 300
  53. EOF
  54. rsync --daemon --config="$CONFIG" && \
  55. echo >&2 "rsync daemon listening on $IP:$PORT"
  56. }
  57. share_woof() {
  58. if command -v guix >/dev/null 2>&1; then
  59. guix environment -C -N --expose="$TARGET"="$TARGET" --ad-hoc woof -- woof -c 9999 -p $PORT "$TARGET" || \
  60. guix environment --ad-hoc woof -- woof -c 9999 -p $PORT "$TARGET"
  61. else
  62. woof -c 9999 -p $PORT "$TARGET"
  63. fi
  64. }
  65. share_python() {
  66. echo >&2 "Python HTTP server will listen on $IP:$PORT."
  67. if command -v guix >/dev/null 2>&1; then
  68. guix environment -C -N --expose="$TARGET"="$TARGET" --ad-hoc python -- \
  69. python3 -m http.server -d "$TARGET" $PORT
  70. elif command -v python3 >/dev/null 2>&1; then
  71. python3 -m http.server -d "$TARGET" $PORT
  72. else
  73. python -m http.server -d "$TARGET" $PORT
  74. fi
  75. }
  76. if [ -f "$TARGET" ]; then
  77. share_woof "$TARGET"
  78. elif $OPT_HTTP; then
  79. share_python "$TARGET"
  80. else
  81. share_rsync
  82. fi