diff --git a/home/stormux/.local/.functions/download.sh b/home/stormux/.local/.functions/download.sh index 6734eaa..e9409cc 100755 --- a/home/stormux/.local/.functions/download.sh +++ b/home/stormux/.local/.functions/download.sh @@ -115,7 +115,8 @@ monitor_download_progress() { local doneFile="$3" local currentBytes=0 local percent=0 - local lastAnnouncedPercent=-10 + local lastAnnouncedPercent=0 + local lastAnnouncedBytes=0 local tickCount=0 while [[ ! -e "$doneFile" ]]; do @@ -130,16 +131,17 @@ monitor_download_progress() { if [[ "$percent" -gt 100 ]]; then percent=100 fi - if [[ "$percent" -ge $((lastAnnouncedPercent + 10)) ]]; then + if [[ "$percent" -gt 0 && "$percent" -ge $((lastAnnouncedPercent + 10)) ]]; then printf 'Downloaded %s%% (%s/%s bytes)\n' "$percent" "$currentBytes" "$totalBytes" >&2 beep_download_progress "$percent" lastAnnouncedPercent="$percent" fi else tickCount="$((tickCount + 1))" - if [[ "$tickCount" -ge 5 ]]; then + if [[ "$currentBytes" -gt "$lastAnnouncedBytes" && "$tickCount" -ge 5 ]]; then printf 'Downloaded %s bytes\n' "$currentBytes" >&2 beep_download_progress 50 + lastAnnouncedBytes="$currentBytes" tickCount=0 fi fi @@ -147,11 +149,29 @@ monitor_download_progress() { done } +stop_download_processes() { + local doneFile="$1" + local monitorPid="$2" + local downloadPid="${3:-}" + + touch "$doneFile" 2> /dev/null || true + if [[ -n "$downloadPid" ]] && kill -0 "$downloadPid" 2> /dev/null; then + kill "$downloadPid" 2> /dev/null || true + wait "$downloadPid" 2> /dev/null || true + fi + if [[ -n "$monitorPid" ]] && kill -0 "$monitorPid" 2> /dev/null; then + kill "$monitorPid" 2> /dev/null || true + wait "$monitorPid" 2> /dev/null || true + fi + rm -f "$doneFile" +} + run_download_command() { local outputPath="$1" local totalBytes="$2" local errorFile="$3" local doneFile + local downloadPid="" local monitorPid local commandStatus=0 shift 3 @@ -160,13 +180,18 @@ run_download_command() { rm -f "$doneFile" monitor_download_progress "$outputPath" "$totalBytes" "$doneFile" & monitorPid="$!" + trap 'stop_download_processes "$doneFile" "$monitorPid" "$downloadPid"; trap - INT TERM HUP; exit 130' INT TERM HUP - "$@" 2> >(tee -a "$errorFile" >&2) - commandStatus="$?" + "$@" 2> >(tee -a "$errorFile" >&2) & + downloadPid="$!" + if wait "$downloadPid"; then + commandStatus=0 + else + commandStatus="$?" + fi - touch "$doneFile" - wait "$monitorPid" 2> /dev/null || true - rm -f "$doneFile" + stop_download_processes "$doneFile" "$monitorPid" + trap - INT TERM HUP return "$commandStatus" }