#!/bin/sh -e
#
# aget [URL] - like wget, but archive the results
#
# ---
# source: https://leahneukirchen.org/dotfiles/bin/aget

url="$1"
base=${url##*/}
date="$(date -I)"
out="${base}-${date}"

for f in "${base}-"????-??-??; do
  [ "${f}" != "${out}" ] && last=${f}
done

# wget -O "${out}" "${url}"
curl -o "${out}" "${url}"

if ! [ -f "${last}" ] || ! cmp "${last}" "${out}"; then
  echo "new ${out}"
  # true if file exists and is executable
  [ -x "${last}" ] && chmod +x "${out}"
  # true if file exists and is a symbolic link
  [ -h "${base}" ] && ln -sf "${out}" "${base}"
else
  echo "unmodified"
  rm -- "${out}"
  false
fi
