#!/bin/bash
#
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2010, 2013, 2014, 2016 Synacor, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software Foundation,
# version 2 of the License.
#
# This program 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 this program.
# If not, see <https://www.gnu.org/licenses/>.
# ***** END LICENSE BLOCK *****
# 

if [ x`whoami` != xzimbra ]; then
    echo Error: must be run as zimbra user
    exit 1
fi

source /opt/zimbra/bin/zmshutil || exit 1
zmsetvars

download_dir=${mailboxd_directory}/webapps/zimbra/downloads

client_file=$1

if [ x${client_file} = "x" ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

client_file_basename=`basename $client_file`

# sed RE
version_re='[0-9]*\.*[0-9]*\.*[0-9]*\.*\(_BETA[^_]*_\)*\(_GA_\)*[0-9][0-9]*'
client_file_appglob=`echo $client_file_basename | sed -e "s/$version_re/*/"`

if [ ! -r ${client_file} ]; then
    echo Error: ${client_file} does not exist or is unreadable
    exit 1
fi

if [ ! -d ${download_dir} ]; then
    echo Error: ${download_dir} does not exist
    exit 1
fi

[ -f /opt/zimbra/bin/zmacl ] && /opt/zimbra/bin/zmacl disable &> /dev/null
cp -f ${client_file} ${download_dir}

if [ $? -ne 0 ]; then
	echo Error: copy failed
        [ -f /opt/zimbra/bin/zmacl ] && /opt/zimbra/bin/zmacl enable &> /dev/null
	exit 1
fi

for file in `ls ${download_dir}/${client_file_appglob}`; do
	if [ ${file} = ${download_dir}/${client_file_basename} ]; then
		continue
	fi
	echo Removing ${file}
	/bin/rm -f ${file}
done

[ -f /opt/zimbra/bin/zmacl ] && /opt/zimbra/bin/zmacl enable &> /dev/null
/opt/zimbra/bin/zmmailboxdctl update
