#!/bin/bash

# basic usage, error and help function
usage() {
  [[ -n $1 ]] && echo -e "\n  $1"
  echo -e "\n  Usage:  ${0##*/} path-to-tde [default ~/tde] dir-to-write-tgz [~/tdetgz] -w [actually write!]\n"
  echo -e "    ${0##*/} will create tarballs from a local copy of the tde git repository layout. The"
  echo -e "    script requires the location of the local copy as the first argument if the tde copy"
  echo -e "    is not present in ~/tde and the directory to write tarballs to [default ~/tdetgz]. The script"
  echo -e "    will output all the tar commands as a test for confirmation. Use the -w option as the"
  echo -e "    third argument to actually create the files.\n"
  echo -e "    Filename format (examples):\n"
  echo -e "      tdepim-admin.tar.gz"
  echo -e "      tdepim-akregator.tar.gz"
  echo -e "      tdepim-certmanager.tar.gz"
  echo -e "      tdepim-cmake.tar.gz\n"
  exit 1
}

# respond to help
[[ $@ =~ -h ]] && usage

# check tde path or show usage
tdepath="${1:-$HOME/tde}"
[[ -r "$tdepath" ]] || usage "ERROR: local copy of tde not found in '$tdepath'" >&2

# check or create output path for tarballs
tgzpath="${2:-$HOME/tdetgz}"
[[ -d "$tgzpath" ]] || mkdir -p "$tgzpath"
[[ -d "$tgzpath" ]] || usage "ERROR: unable to create output directory '$tgzpath' for .tar.gz files, exiting." >&2

# save present working dir and change to tdepath
mydir=$PWD
cd "$tdepath" || usage "Error: unable to change to tde directory '$tdepath'" >&2

# verify main directory and load array or exit
[[ -d main ]] || usage "Error no 'main' directory found in '$tdepath'" >&2
declare -a tdedirs
tdedirs=( $(find main/ -maxdepth 2 -type d | sort) )

# create your tarballs
for((i=0;i<${#tdedirs[@]};i++)); do

  # set current directory
  current="${tdedirs[$i]}"

  # skip parent directories
  isparent="${current%/*}"
  [[ "$isparent" =~ / ]] || { parent=${current##*/}; echo "parent: $parent"; continue; }

  # create tarballs with parent-name prefix to prevent name clashes (-w required to actually create files)
  if [[ $@ =~ '-w' ]]; then
    echo -n "Compressing ${parent}-${current##*/}.tar.gz .... "
    tar -C ${tdepath}/${current%/*} -czf ${tgzpath}/${parent}-${current##*/}.tar.gz ${current##*/}
    echo "     done"
  else
    echo "tar -C ${tdepath}/${current%/*} -czf ${tgzpath}/${parent}-${current##*/}.tar.gz ${current##*/}"
  fi

done

# cleanup and resore workind directory
cd "$mydir"

exit 0
