megasync.sh 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #! /usr/bin/env sh
  2. getremotefile()
  3. {
  4. localtmpdir="$(mktemp -d -p $1)"
  5. localtmpfile="${localtmpdir}/${3}"
  6. localfile="${1}/${3}"
  7. backupfile="${localfile}_backup_$(date)"
  8. megaget --no-progress --path "$localtmpfile" "$2" && echo "Downloaded $2 successfully!"
  9. mv "$localfile" "$backupfile" && mv "$localtmpfile" "$localfile" && echo "Synced and replaced successfully!"
  10. }
  11. sendremotefile()
  12. {
  13. megarm "$1"
  14. megaput --no-progress --path "$1" "$2" && echo "Uploaded $1 successfully!"
  15. }
  16. # CONFIG
  17. SYNCEDDIR=~/docs
  18. SYNCEDFILE=base_ultimate.kdbx
  19. REMOTEFILEPATH=/Root/sync/base_ultimate.kdbx
  20. THRESHOLDINSECONDS=7200 # 2h difference
  21. # CONFIG
  22. test ! -d $SYNCEDDIR && echo "Synced path doesn't exist, quitting..." && exit 1
  23. REMOTEFLINE="$(megals -l --reload | grep "$REMOTEFILEPATH")"
  24. test -z "$REMOTEFLINE" && echo "Failed to get remote file stat, quitting..." && exit 2
  25. REMOTEDATE="$(echo "$REMOTEFLINE" | awk '{ print $5, $6 }')"
  26. LOCALFLINE="$(stat -c %y "${SYNCEDDIR}/${SYNCEDFILE}")"
  27. test -z "$LOCALFLINE" && "Failed to get local file stat, quitting..." && exit 3
  28. LOCALDATE="$(stat -c %y "${SYNCEDDIR}/${SYNCEDFILE}" | sed -e 's/\..*//g')"
  29. echo "Remote: ${REMOTEDATE}"
  30. echo "Local: ${LOCALDATE}"
  31. DIFFSECONDS=$(echo "$(($(date -d "$REMOTEDATE" +%s) - $(date -d "$LOCALDATE" +%s)))")
  32. ABSDIFFSECONDS=$DIFFSECONDS
  33. test $ABSDIFFSECONDS -lt "0" && ABSDIFFSECONDS=$(echo "$ABSDIFFSECONDS * -1" | bc -l)
  34. test $ABSDIFFSECONDS -lt $THRESHOLDINSECONDS && echo "Remote and local are close enough in time (${DIFFSECONDS}s), exitting..." && exit 0
  35. echo "Local and remote are too far apart (${DIFFSECONDS}s), syncing..."
  36. test $DIFFSECONDS -lt "0" && echo "Remote is too old!" && sendremotefile "$REMOTEFILEPATH" "${SYNCEDDIR}/${SYNCEDFILE}"
  37. test $DIFFSECONDS -gt "0" && echo "Local is too old!" && getremotefile "$SYNCEDDIR" "$REMOTEFILEPATH" "$SYNCEDFILE"
  38. exit 0