#!bash
# vim:ff=unix:enc=utf8:ts=3:sw=3:et

# src2pkg-ng - package creation toolkit
# Copyright (C) 2005-2009 Gilbert Ashley
# Copyright (C) 2009 Timothy Goya

# src2pkg-ng is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2 as 
# published by the Free Software Foundation

# src2pkg-ng is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with src2pkg-ng.  If not, see <http://www.gnu.org/licenses/>.

get_color_code() {
   declare COLOR="$1"
   declare CODE=""
   if [[ "$COLOR" == bold* ]] ; then
      CODE="$CODE$(tput bold)"
      COLOR="${COLOR#bold }"
   fi
   case $COLOR in
      black)
         CODE="$CODE$(tput setaf 0)"
      ;;
      red)
         CODE="$CODE$(tput setaf 1)"
      ;;
      green)
         CODE="$CODE$(tput setaf 2)"
      ;;
      yellow)
         CODE="$CODE$(tput setaf 3)"
      ;;
      blue)
         CODE="$CODE$(tput setaf 4)"
      ;;
      magenta)
         CODE="$CODE$(tput setaf 5)"
      ;;
      cyan)
         CODE="$CODE$(tput setaf 6)"
      ;;
      white)
         CODE="$CODE$(tput setaf 7)"
      ;;
   esac
   echo "$CODE"
}

make_color_tag() {
   declare TAG="$1"
   declare COLOR="$2"
   eval "format_$TAG() { echo \"\$(get_color_code \"$COLOR\")\$1\$(tput \"sgr0\")\"; }"
}

tprintf() {
   declare FORMAT="$1"
   shift 1
   declare TAG_RE="@([[:alpha:]][[:alnum:]]*)\{([^\}]*)\}"
   while [[ "$FORMAT" =~ $TAG_RE ]] ; do
      declare TAG="${BASH_REMATCH[1]}"
      declare TEXT="${BASH_REMATCH[2]}"
      if [[ "$USE_COLORS" == "always" ]] || [[ "$USE_COLORS" == "auto" && -t 1 ]] ; then
         FORMAT="${FORMAT/"${BASH_REMATCH[0]}"/$(format_$TAG "$TEXT")}"
      else
         FORMAT="${FORMAT/"${BASH_REMATCH[0]}"/$TEXT}"
      fi
   done
   printf "$FORMAT" "$@"
}

push_back() {
   declare ARRAY="$1"
   shift 1
   set +u
   eval "$ARRAY=(\"\${$ARRAY[@]}\" \"\$@\")"
   set -u
}

push_front() {
   declare ARRAY="$1"
   shift 1
   set +u
   eval "$ARRAY=(\"\$@\" \"\${$ARRAY[@]}\")"
   set -u
}
