#!/bin/bash

# A simple script to checkout or update a svn or git repo as source service

# defaults
MYARCHIVE=""
MYFILES=""
OUTFILE="."

while test $# -gt 0; do
  case $1 in
    *-archive)
      MYARCHIVE="${2##*/}"
      shift
    ;;
    *-file|*-files)
      MYFILES="$MYFILES ${2}"
      shift
    ;;
    *-outfilename)
      OUTFILE="${2}"
      shift
    ;;
    *-outdir)
      MYOUTDIR="$2"
      shift
    ;;
    *)
      echo Unknown parameter $1.
      echo 'Usage: extract_file --archive $ARCHIVE --file $FILE --outdir $OUT'
      exit 1
    ;;
  esac
  shift
done

if [ -z "$MYARCHIVE" ]; then
  echo "ERROR: no archive specified!"
  exit 1
fi
if [ -z "$MYFILES" ]; then
  echo "ERROR: no checkout URL is given via --file parameter!"
  exit 1
fi
if [ -z "$MYOUTDIR" ]; then
  echo "ERROR: no output directory is given via --outdir parameter!"
  exit 1
fi

# If $MYARCHIVE is a glob, there could be multiple tarballs matching it,
# in which case take the most recent one.
existing_archive="$PWD/$(ls -t $MYARCHIVE | head -n1)"

if [[ $existing_archive == "$PWD/" ]];then
  echo "No matching archive found"
  exit 1
fi

if [[ ! -f "$existing_archive" ]];then
  echo "File $existing_archive is not a regular file!"
  exit 1
fi

echo "Extracting from $existing_archive:"
echo "  $MYFILES"

cd "$MYOUTDIR"

if [ "${existing_archive%.tar.gz}" != "$existing_archive" ]; then
  tar xfz "$existing_archive" --wildcards -- $MYFILES || exit 1
elif [ "${existing_archive%.tar.bz2}" != "$existing_archive" ]; then
  tar xfj "$existing_archive" --wildcards -- $MYFILES || exit 1
elif [ "${existing_archive%.tar.xz}" != "$existing_archive" ]; then
  tar xfJ "$existing_archive" --wildcards -- $MYFILES || exit 1
elif [ "${existing_archive%.tar}" != "$existing_archive" ]; then
  tar xf "$existing_archive" --wildcards -- $MYFILES || exit 1
elif [ "${existing_archive%.zip}" != "$existing_archive" ]; then

  for f in $MYFILES; do 
    if [ "${f#-}" != "$f" ]; then 
      echo "illegal --file option: $f" 
      exit 1 
    fi 
  done
  unzip "$existing_archive" $MYFILES || exit 1

elif [ "${existing_archive%.obscpio}" != "$existing_archive" ]; then
  cpio --quiet --extract --preserve-modification-time --make-directories -- $MYFILES < "$existing_archive"
else
  echo "ERROR: unknown archive format $existing_archive"
  exit 1
fi

for i in $MYFILES; do 
  mv -- "$i" "$OUTFILE"
done

# Clean up hierarchy of empty directories - the only files extracted
# within the unpacked archive should already have been moved to
# $OUTFILE.  This is necessary to prevent empty directories being
# transferred back into the checked-out package's working directory,
# which could cause subsequent "osc service disabledrun" invocations
# to fail.
#
# This approach uses rmdir which should be safer than an rm -rf.  The
# tac is necessary to ensure we remove the deepest directories first.
find -type d -printf '%P\n' | tac | xargs -r rmdir

exit 0
