#!/bin/bash

###########################################################
## Copyright (c) 2002-2024 Alexey Kuryakin daqgroup@mail.ru
###########################################################

###########################################################
## fc-aliases - show list of (well known) font aliases.
###########################################################

###########################################################
source $(crwkit which crwlib_base.sh); # Use base library #
###########################################################

let fatal_notify_uses=0;
readonly fonts_conf="fonts.conf";
readonly local_conf="/etc/fonts/local.conf";
readonly home_fonts="$HOME/.config/fontconfig";
declare -a aliases=();

function init_aliases(){
 if [ ${#aliases[@]} -eq 0 ]; then
  aliases+=(monospace);
  aliases+=(sans serif sans-serif);
  aliases+=(Arial Helvetica Verdana);
  aliases+=("Times New Roman" "Courier New");
 fi;
};

function fc_aliases(){
 for family in "$@"; do
  echo -n "$family: ";
  fc-match "$family" | sed -e 's/\" \"/\": \"/' -e 's/\"//g';
 done;
};

function fonts_aliases(){
 init_aliases;
 fc_aliases "${aliases[@]}" | column -t -s ':' | sed 's/  \b/ : /g';
};

function fonts_setup(){
 local source="$scriptHOME/$fonts_conf";
 if [ -e $source ]; then
  if [ "x$1" = "xsystem" ]; then
   local sudo="sudo -n";
   local target="$local_conf";
  else
   local sudo="";
   local target="$home_fonts/$fonts_conf";
   if [ ! -e $(dirname $target)/ ]; then mkdir -pv $(dirname $target); fi;
  fi;
  if [ -e $target ]; then eval $sudo mv -nv $target $target.old; fi;
  eval $sudo cp -fv $source $target;
 else
  fatal 1 "Error: not found $fonts_conf";
 fi;
};

function fonts_remove(){
 local source="$scriptHOME/$fonts_conf";
 if [ -e $source ]; then
  if [ "x$1" = "xsystem" ]; then
   local sudo="sudo -n";
   local target="$local_conf";
  else
   local sudo="";
   local target="$home_fonts/$fonts_conf";
   if [ ! -e $(dirname $target)/ ]; then mkdir -pv $(dirname $target); fi;
  fi;
  if [ -e $target ]; then eval $sudo rm -fv $target; fi;
  if [ -e $target.old ]; then eval $sudo mv -nv $target.old $target; fi;
 else
  fatal 1 "Error: not found $fonts_conf";
 fi;
};

function main(){
 case $1 in
  list)   fonts_aliases; ;;
  setup)  fonts_setup  "$2"; ;;
  remove) fonts_remove "$2"; ;;
  *)      fatal 1 "$scriptname list | setup [system] | remove [system]"; ;;
 esac;
};

main "$@";

##############
## END OF FILE
##############
