summaryrefslogtreecommitdiffstats
path: root/bin/unpack-zipped-xml.sh
blob: ac22fe9b6822368224d9f0afccbb3fa6d1ffcc89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env bash

# global constants
outdir=xml

function abort()
{
    (>&2 echo "$1")  # output to stderr
    exit 1
}

filepath="$1"

if [ -z "$filepath" ]; then
    abort "file path is not given."
fi

shift

# convert the file path to absolute path.
filepath=`realpath "$filepath"`

# remove existing output directory if one exists.
if [ -d $outdir ]; then
    rm -rf $outdir || abort "failed to remove the existing output directory '$outdir'."
fi

mkdir $outdir || abort "failed to create an output directory '$outdir'."

# unzip all inside the output directory.
cd $outdir
unzip "$filepath" > /dev/null || abort "failed to unzip $filepath."

# temporarily replace bash's internal field separators to handle file names with spaces.
_IFS="$IFS"
IFS=$'\n'

for _file in $(find . -type f); do
    _mimetype=`file --mime-type --brief "$_file"` || abort "failed to determine the mime type of $_file."
    if [ $_mimetype = "application/xml" ] || [ $_mimetype = "text/xml" ]; then
        # beautify the XML file content.
        _temp=$(mktemp) || abort "failed to create a temporary file."
        xmllint --format $_file > $_temp || abort "failed to run xmllint on $_file."
        mv $_temp $_file || abort "failed to update $_file."
    fi
done

# restore the original separators.
IFS="$_IFS"