#!/bin/sh
# Copyright (c) 2000-2016 Synology Inc. All rights reserved.
PACKAGE_NAME="VPNPlusServer"
PKG_USERCONF_DIR="/usr/syno/etc/packages/${PACKAGE_NAME}"
OLD_VERSION_FILE="old_version"
REPORT_TOOL="syno_traffic_report_tool"
SQLITE3="/usr/syno/bin/sqlite3"
DB_NAME="synovpnplus.db"
RDP_CONF="$PKG_USERCONF_DIR/remotedesktop/synoremotedesktop.conf"
VPN_PLUS_CONF="$PKG_USERCONF_DIR/synovpnplus.conf"
WP_HTTPD_CONF="/etc/httpd/sites-enabled/SYNO.SDS.VPNPlus.WebPortal.Application.alt_port_ssl.conf"
RDP_HTTPD_CONF="/etc/httpd/sites-enabled/SYNO.SDS.VPNPlus.WebPortal.Application.RemoteDesktop.alt_port_ssl.conf"
GET_KV="/bin/get_key_value"
GET_SECT_KV="/usr/syno/bin/get_section_key_value"

# Real uninstall
if [ "x$SYNOPKG_PKG_STATUS" != "xUPGRADE" ]; then
	if [ -e $WP_HTTPD_CONF ]; then
		rm $WP_HTTPD_CONF;
	fi

	if [ -e $RDP_HTTPD_CONF ]; then
		rm $RDP_HTTPD_CONF;
	fi

	rdp_enable=`$GET_KV $RDP_CONF enable`
	sslvpn_enable=`$GET_SECT_KV $VPN_PLUS_CONF sslvpn enable`
	webvpn_enable=`$GET_SECT_KV $VPN_PLUS_CONF webportal enable`
	if [ "yes" = "$rdp_enable" -o "yes" = "$sslvpn_enable" -o "yes" = "$webvpn_enable" ]; then
		synoservicecfg --reload httpd-sys
	fi

	if [ "x$pkgwizard_remove_synovpnplus_setting" != "xtrue" ]; then
		# checkpoint the db
		${SQLITE3} "${PKG_USERCONF_DIR}/db/${DB_NAME}" "PRAGMA wal_checkpoint;"

		echo old_version=${SYNOPKG_PKGVER} > ${PKG_USERCONF_DIR}/${OLD_VERSION_FILE}
	else
		# Remove user config dir
		rm -rf ${PKG_USERCONF_DIR}
	fi

	if [ "x$pkgwizard_remove_synovpnplus_report" == "xtrue" ]; then
		${REPORT_TOOL} --clear_reports --reporter_id ${PACKAGE_NAME}
	fi

	# Remove reserver server ip
	sed -i '/vpnplus-/d' /etc/dhcpd/dhcpdStatic.ori
	/usr/syno/sbin/synodhcpserver --reload

	${REPORT_TOOL} --unregister --reporter_id ${PACKAGE_NAME}
fi

exit 0
