#!/usr/bin/env bash

histfile="$1"
if_more_than_lines="$2"
to_lines="$3"

lines=$(wc -l <"${histfile}")
if [ "${lines}" -gt "${if_more_than_lines}" ]; then
  mkdir -p ~/.gnu_bash_history.eternal
  archive=~/.gnu_bash_history.eternal/"$(date +%F--%H-%M-%S)--pid$$.xz"

  echo "Archiving Bash history to '${archive}' ..."

  head -n -"${to_lines}" <"${histfile}" | xz -9 >"${archive}"

  tmpfile=$(mktemp)
  tail -n "${to_lines}" <"${histfile}" >"${tmpfile}"
  mv "${tmpfile}" "${histfile}"
fi
