#!/bin/sh

PKG_VOL_TMP="/`/usr/bin/readlink /var/services/homes | /usr/bin/cut -d'/' -f2`/@tmp"
SYS_VOL="/`/usr/bin/readlink /var/services/homes | /usr/bin/cut -d'/' -f2`"

mailstation=/usr/syno/mailstation
WebMailDir="/var/packages/MailStation/target"
WebMailExt=${WebMailDir}/mail/ext
OLDVERSION=`cat /tmp/MailStation.upgrade`
NEWVERSION=`grep ^version /var/packages/MailStation/INFO | cut -d'"' -f2 | cut -d'-' -f2`

WebMailConf=${WebMailDir}/mail/config/config.inc.php

UPDATE_SCRIPT_FOLDER="/var/packages/MailStation/target/mail/SQL/postgres"
SUDO="su MailStation -s /bin/sh -c"
PGSQL=/usr/bin/psql
DB_USER="postgres"
DB_OWNER="MailStation"
DB_NAME="roundcubemail"

touch ${WebMailDir}/mail/logs/upgrade
chmod 755 ${WebMailDir}/mail/logs/upgrade

update_username()
{
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"select user_id from users_type where account_type='ldap';\"" | sed '1,2d' | while read user_id
	do
		if [ x"(" = x"${user_id:0:1}" ]; then
			break;
		fi
		domain_name=`${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"select domain_name from users_type where user_id=${user_id};\"" | sed '1,2d;4d' | tr -d ' '`
		username=`${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"select username from users where user_id=${user_id};\"" | sed '1,2d;4d' | tr -d ' '`
		username=${username}'@'${domain_name}
		`${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"BEGIN;UPDATE users SET username='${username}' where user_id=${user_id};END;\""`
	done

	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"select user_id from users_type where account_type='win';\"" | sed '1,2d' | while read user_id
	do
		if [ x"(" = x"${user_id:0:1}" ]; then
			break;
		fi

		domain_name=`${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"select domain_name from users_type where user_id=${user_id};\"" | sed '1,2d;4d' | tr -d ' '`
		username=`${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"select username from users where user_id=${user_id};\"" | sed '1,2d;4d' | tr -d ' '`
		username=${domain_name}'\\'${username}
		`${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"BEGIN;UPDATE users SET username='${username}' where user_id=${user_id};END;\""`
	done

}

parse_short_username()
{
	local full_username=$1
	local short_username=

	if [[ "${full_username}" == *"@"* ]];then
		#ldap user
		short_username=$(echo "${full_username}" | sed 's/\(.*\)@.*/\1/')
	elif [[ "${full_username}" == *"\\"* ]]; then
		#domain user
		short_username=$(echo "${full_username}" | sed 's/.*\\\(.*\)/\1/')
	else
		short_username=${full_username}
	fi
	echo "${short_username}"
}

upgrade_ext_fetchmail()
{
	local old_version=$1
	local filename="$2"
	local filepath="${WebMailExt}/${filename}"
	local owner=$(stat -c "%U" "${filepath}")

	echo "upgrade ext file: ${filepath}" >> ${WebMailDir}/mail/logs/upgrade

	if [ "${owner}" == "UNKNOWN" ]; then
		owner=$(echo "${filename}" | sed 's/\(.*\)\.proc\..*/\1/')
	fi

	local filepath_bak="/tmp/${filename}.bak"
	cp -p "${filepath}" "${filepath_bak}"
	if [ "${old_version}" -le 279 ]; then
		grep "DELIVER" "${filepath}" > /dev/null 2>&1
		if [ 0 -ne $? ]; then
			sed -i "6iDELIVER=\"/var/packages/MailServer/target/libexec/dovecot/dovecot-lda\"" "${filepath_bak}"
			local store_mailbox=$(tail -1 "${filepath}")
			if [ ".Maildir/" = "${store_mailbox}" ]; then
				sed -i "$ s/.Maildir\//| \$DELIVER/g" "${filepath_bak}"
			fi
		fi
	fi
	local short_username=$(parse_short_username "${owner}")
	sed -i "s/^| \\\$DELIVER$/| \$DELIVER -d \"${short_username}\"/" "${filepath_bak}"

	mv "${filepath_bak}" "${filepath}"

	echo "Upgraded ${filepath} to new version" >> ${WebMailDir}/mail/logs/upgrade
}

upgrade_ext_all_fetchmail()
{
	local old_version=$1
	ls "${WebMailExt}" | grep "proc" | grep -v "procmailrc" | while read -r fetchmail_config
	do
		upgrade_ext_fetchmail "${old_version}" "${fetchmail_config}"
	done
}

echo Upgrade from version ${OLDVERSION} to version ${NEWVERSION} >> ${WebMailDir}/mail/logs/upgrade

#we need change database owner before any database operation
SYNOPGSQL="/usr/syno/bin/synopsql"
if [ -f ${SYNOPGSQL} ]; then
	${SYNOPGSQL} --change-own ${DB_NAME} ${DB_OWNER}
fi

if [ $OLDVERSION -le 16 -a $NEWVERSION -ge 17 ]; then
	UPGRADE_SQL="/var/packages/MailStation/target/mail/plugins/mailstation/SQL/postgres.update.sql"
	if [ -f ${UPGRADE_SQL} ]; then
		${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPGRADE_SQL} >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	fi
fi

if [ $OLDVERSION -le 18 -a $NEWVERSION -ge 19 ]; then
	UPGRADE_SQL="/var/packages/MailStation/target/mail/plugins/mailstation/SQL/postgres.syno.update.sql"
	if [ -f ${UPGRADE_SQL} ]; then
		${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPGRADE_SQL} >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	fi
fi
if [ $OLDVERSION -le 46 -a $NEWVERSION -ge 47 ]; then
	UPGRADE_SQL="/var/packages/MailStation/target/mail/plugins/mailstation/SQL/postgres.syno.domain.update.sql"
	if [ -f ${UPGRADE_SQL} ]; then
		${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPGRADE_SQL} >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	fi
fi
if [ $OLDVERSION -eq 47 -a $NEWVERSION -ge 48 ]; then
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \"BEGIN;UPDATE users_type SET account_type='local' WHERE account_type='';END;\" 2>&1"
fi

if [ $OLDVERSION -eq 62 -a $NEWVERSION -ge 63 ] || [ $OLDVERSION -eq 61 -a $NEWVERSION -ge 63 ]; then
	update_username
	#updates=("2010100600.sql" "2011011200.sql" "2011092800.sql" "2011111600.sql" "2011121400.sql" "2012080700.sql" "2013011000.sql" )
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/2010100600.sql >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/2011011200.sql >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/2011092800.sql >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/2011111600.sql >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/2011121400.sql >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/2012080700.sql >> ${WebMailDir}/mail/logs/upgrade 2>&1"
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/2013011000.sql >> ${WebMailDir}/mail/logs/upgrade 2>&1"
fi

if [ $OLDVERSION -le 199 ]; then
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \
	\"BEGIN;
	ALTER TABLE popinfo ADD COLUMN popservice_provider text;
	UPDATE popinfo SET popservice_provider='custom';
	END;\" >> ${WebMailDir}/mail/logs/upgrade 2>&1"
fi

if [ $OLDVERSION -le 201 ]; then
	update_scripts="2013042700.sql 2013052500.sql 2013061000.sql"
	for script in ${update_scripts}
	do
		${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/${script} ${WebMailDir}/mail/logs/upgrade 2>&1"
	done

	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \
	\"BEGIN;
	ALTER SEQUENCE smtp_ids RENAME TO smtp_seq;
	ALTER TABLE smtp ALTER COLUMN smtp_id SET DEFAULT nextval('smtp_seq'::text);
	ALTER SEQUENCE users_type_ids RENAME TO users_type_seq;
	ALTER TABLE users_type ALTER COLUMN users_type_id SET DEFAULT nextval('users_type_seq'::text);
	END;\" >> ${WebMailDir}/mail/logs/upgrade 2>&1"
fi

if [ $OLDVERSION -le 208 ]; then
	${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} -c \
	\"BEGIN;
	ALTER TABLE smtp ADD COLUMN smtp_ssl integer;
	ALTER TABLE smtp RENAME iftls TO smtp_tls;
	UPDATE smtp SET smtp_ssl=0;
	END;\" >> ${WebMailDir}/mail/logs/upgrade 2>&1"
fi

if [ $OLDVERSION -le 256 ]; then
	if [ -d "/tmp/MailStation/ext" ]; then
		ls "/tmp/MailStation/ext/" | grep "_fetch" | while read fetchmail_config
		do
			sed -i -e "s|\/var\/packages\/MailStation\/target\/roundcubemail|\/var\/packages\/MailStation\/target\/mail|g" "/tmp/MailStation/ext/${fetchmail_config}"
		done
	fi
fi

/bin/grep -Ev "config.*extmailallow|config.*extmailperiod|config.*smtp_server|config.*smtp_port|config.*mail_domain" ${WebMailConf} > /tmp/MailStation.$$

/bin/cat /tmp/MailStation.restore >> /tmp/MailStation.$$
/bin/mv /tmp/MailStation.$$ ${WebMailConf}
chown MailStation:MailStation ${WebMailConf}


rm -f /tmp/MailStation.upgrade
rm -f /tmp/MailStation.restore

if [ -d /tmp/MailStation/ext ]; then
	/bin/cp -a /tmp/MailStation/ext ${WebMailDir}/mail
	chown MailStation:MailStation ${WebMailDir}/mail/ext
	chown -R MailStation:MailStation ${WebMailDir}/mail/ext/.cert
	/bin/rm -rf /tmp/MailStation/ext > /dev/null 2>&1
fi

sed -i 's/\/usr\/syno\/mailstation\/sbin\/procmail/\/var\/packages\/MailStation\/target\/bin\/procmail/g' ${WebMailDir}/mail/ext/*_fetch

if [ "$OLDVERSION" -le 299 ]; then
	upgrade_ext_all_fetchmail "$OLDVERSION"
fi

if [ "$OLDVERSION" -le 281 ]; then
	update_scripts="2015111100.sql"
	for script in ${update_scripts}
	do
		${SUDO} "${PGSQL} -U ${DB_USER} ${DB_NAME} < ${UPDATE_SCRIPT_FOLDER}/${script} ${WebMailDir}/mail/logs/upgrade 2>&1"
	done
fi

NGINX_CONF_DIR="/usr/local/etc/nginx/conf.d/"
[ -f "$NGINX_CONF_DIR/www.MailStation.conf" ] && rm -f "$NGINX_CONF_DIR/www.MailStation.conf"

exit 0


