744d354880bb8c7e472c3615cc0ff3b940ce584f
[feisty_meow.git] / scripts / archival / unpack.sh
1 #!/bin/bash
2
3 ##############
4 # Name   : unpack
5 # Author : Chris Koeritz
6 # Rights : Copyright (C) 2012-$now by Feisty Meow Concerns, Ltd.
7 ##############
8 # This script is free software; you can modify/redistribute it under the terms
9 # of the GNU General Public License. [ http://www.gnu.org/licenses/gpl.html ]
10 # Feel free to send updates to: [ fred@gruntose.com ]
11 ##############
12 #
13 # An arbitrary format archive unpacker, although really we are mainly supporting
14 # tar and zip currently, including compressed formats.
15
16 archive_file="$1"; shift
17 if [ -z "$archive_file" ]; then
18   echo "This script takes one archive name (in .tar.gz, .zip, etc. formats) and"
19   echo "unpacks the archive with the appropriate tool."
20   exit 1
21 fi
22 if [ ! -f "$archive_file" ]; then
23   echo "The file specified cannot be located: $archive_file"
24   exit 1
25 fi
26 unpack_dir="$1"; shift
27 if [ -z "$unpack_dir" ]; then
28   unpack_dir=$(echo arch_$(basename $archive_file) | sed -e 's/^\([^\.]*\)\..*/\1/')
29 fi
30
31 if [ ! -d "$unpack_dir" ]; then
32   mkdir "$unpack_dir"
33   if [ $? -ne 0 ]; then
34     echo "Could not create the unpacking directory: $unpack_dir"
35     exit 1
36   fi
37 fi
38
39 # save where we started out.
40 ORIGINATING_FOLDER="$( \pwd )"
41
42 pushd "$unpack_dir" &>/dev/null
43
44 if [ ! -f "$archive_file" ]; then
45   # we're assuming we left it behind in our previous directory.
46   archive_file="$ORIGINATING_FOLDER/$archive_file"
47   if [ ! -f "$archive_file" ]; then
48     echo "Could not find file to unpack after shifting directories.  Sorry."
49     echo "Tried to locate it as: $archive_file"
50     exit 1
51   fi
52 fi
53
54 if [[ $archive_file =~ .*\.tar$ \
55     || $archive_file =~ .*\.tar\.gz$ \
56     || $archive_file =~ .*\.tar\.bz2$ \
57     || $archive_file =~ .*\.iar$ \
58     || $archive_file =~ .*\.oar$ \
59     || $archive_file =~ .*\.tgz$ \
60     || $archive_file =~ .*\.ova$ \
61     ]]; then
62   tar -xf $archive_file &>/dev/null
63 elif [[ $archive_file =~ .*\.zip$ \
64     || $archive_file =~ .*\.epub$ \
65     || $archive_file =~ .*\.odt$ \
66     || $archive_file =~ .*\.jar$ \
67     || $archive_file =~ .*\.war$ \
68     ]]; then
69   unzip $archive_file &>/dev/null
70 fi
71 save_err=$?
72
73 popd &>/dev/null
74
75 if [ $save_err -ne 0 ]; then
76   echo "There was a failure reported while unpacking: $archive_file"
77   echo "into the directory: $unpack_dir"
78   exit 1
79 else
80   echo "Unpacked file $(basename $archive_file) into folder: $unpack_dir"
81 fi
82
83