#!/usr/bin/env bash

# back up a file by copying it to a new file with a .bak extension
# reference: https://askubuntu.com/questions/962489/is-there-any-way-to-create-backup-copy-of-a-file-without-type-its-name-twice

usage() {
  echo "Usage: bak [-t|--timestamp] <file to back up>"
  exit 1
}

timestamp=false

while [[ $# -gt 0 ]]; do
  case $1 in
    -t|--timestamp)
      timestamp=true
      shift
      ;;
    *)
      break
      ;;
  esac
done

[ $# -eq 1 ] || usage

if $timestamp; then
  date="$(date +%Y-%m-%d_%H-%M-%S)"
  cp -vpn "$1"{,."$date".bak}
else
  cp -vpn "$1"{,.bak}
fi
