#!/usr/bin/env bash

# === [ Config ] === #
DRIVERS_DIR="drivers"
# (relative paths are resolved from this script's folder)

if [[ -t 1 ]]; then B=$'\e[1m'; BL=$'\e[1;34m'; RD=$'\e[1;31m'; GR=$'\e[1;32m'; R=$'\e[0m'
else B=; BL=; RD=; GR=; R=; fi

has() { command -v "$1" >/dev/null 2>&1; }

deps=(readlink:coreutils stat:coreutils numfmt:coreutils sort:coreutils
      rm:coreutils dirname:coreutils sed:sed)
report="${BL}::${R} ${B}Checking dependencies...${R}"$'\n'
missing=0

if (( BASH_VERSINFO[0] >= 4 )); then
  report+="  $(printf '%-10s' 'bash >= 4') ${GR}ok${R} (${BASH_VERSION%%[( ]*})"$'\n'
else
  report+="  $(printf '%-10s' 'bash >= 4') ${RD}missing${R} (found ${BASH_VERSION%%[( ]*})"$'\n'
  missing=$((missing + 1))
fi
for d in "${deps[@]}"; do
  bin="${d%%:*}"; pkg="${d##*:}"
  if has "$bin"; then
    report+="  $(printf '%-10s' "$bin") ${GR}ok${R}"$'\n'
  else
    report+="  $(printf '%-10s' "$bin") ${RD}missing${R} (package: $pkg)"$'\n'
    missing=$((missing + 1))
  fi
done

printf '%s\n' "$report"
if (( missing > 0 )); then
  echo "${RD}error:${R} $missing required dependenc$( ((missing==1)) && echo y || echo ies ) missing."
  echo "This script can't run without them. Install them and try again."
  exit 1
fi

script_dir="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
DRIVERS_DIR="${DRIVERS_DIR/#\~/$HOME}"
[[ "$DRIVERS_DIR" == /* ]] && dir="$DRIVERS_DIR" || dir="$script_dir/$DRIVERS_DIR"
yes=0
for a in "$@"; do [[ "$a" == "-y" ]] && yes=1 || dir="$a"; done
cd "$dir" || { echo "error: can't open $dir"; exit 1; }
shopt -s nullglob

human() { numfmt --to=iec-i --suffix=B --format=%.1f "$1"; }

old=(); keep=(); sizes=()
for base in $(printf '%s\n' DP_*_[0-9]*.7z | sed 's/_[0-9]*\.7z$//' | sort -u); do
  mapfile -t files < <(printf '%s\n' "${base}"_[0-9]*.7z | sort -V)
  keep+=("${files[-1]}")
  old+=("${files[@]:0:${#files[@]}-1}")
done

if (( ${#old[@]} == 0 )); then echo " there is nothing to do"; exit 0; fi

total=0; echo "${B}Old driver packs (${#old[@]}):${R}"
echo
for f in "${old[@]}"; do
  s=$(stat -c %s -- "$f"); sizes+=("$s"); total=$((total + s))
  printf '  %-45s %12s\n' "$f" "$(human "$s")"
done
echo
echo "${B}Total Removed Size:${R}  $(human "$total")"
echo "${B}Newest packs kept:${R}   ${#keep[@]}"
echo

if (( ! yes )); then
  read -r -p "${BL}::${R} ${B}Proceed with removal? [y/N] ${R}" ans
  [[ "${ans,,}" == y || "${ans,,}" == yes ]] || exit 1
fi

echo "${BL}::${R} ${B}Removing old driver packs...${R}"
n=${#old[@]}; i=0; fail=0; freed=0
for f in "${old[@]}"; do
  i=$((i + 1))
  printf '(%*d/%d) removing %-42s ' "${#n}" "$i" "$n" "$f"
  if rm -- "$f" 2>/dev/null; then
    freed=$((freed + sizes[i-1])); echo "${GR}[done]${R}"
  else
    fail=$((fail + 1)); echo "${RD}[fail]${R}"
  fi
done

echo
if (( fail > 0 )); then
  echo "${RD}error:${R} failed to remove $fail of $n files"
  echo "${BL}::${R} ${B}Removed $((n - fail)) files, freed $(human "$freed")${R}"
  exit 1
fi
echo "${BL}::${R} ${B}Removed $n files, freed $(human "$freed")${R}"
