#!/bin/bash

function start_rocketchat {
	echo "Checking if oplog has been enabled, and enabling if not"
	LC_ALL=C mongo $SNAP/bin/initreplset.js
	
	echo "Checking if mongo featureCompatibilityVersion is correct, changing if not"
        db_version=$(mongo --eval "printjson(db.version())" |tail -1 |tr -d '"' |cut -d. -f1,2)
        db_comp_version=$(mongo --eval "printjson(db.adminCommand ({getParameter: 1, featureCompatibilityVersion: 1}))"|grep '"version" :' |cut -d: -f3 |cut -d} -f1|tr -d '[:space:]'|tr -d '"')
        db_featureCompatibilityVersion="$(snapctl get db-feature-compatibility-version)"
        if [[ $db_version == "3.6" ]] && [[ $db_comp_version == "3.4" ]] && [[ $db_featureCompatibilityVersion == "3.6" ]]; then
            LC_ALL=C mongo --eval "printjson(db.adminCommand ({ setFeatureCompatibilityVersion: \"3.6\" }))"
        fi
	
	## For making fonts work for sharp
	export XDG_DATA_HOME=$SNAP/usr/share

	# Font Config
	export FONTCONFIG_PATH=$SNAP/etc/fonts/config.d
	export FONTCONFIG_FILE=$SNAP/etc/fonts/fonts.conf


	export DEPLOY_METHOD=snap
	export NODE_ENV=production
	export BABEL_CACHE_DIR=/tmp
	export ROOT_URL=http://localhost
        export PORT="$(snapctl get port)"
        export MONGO_URL="$(snapctl get mongo-url)"
        export MONGO_OPLOG_URL="$(snapctl get mongo-oplog-url)"
	export Accounts_AvatarStorePath=$SNAP_COMMON/uploads
	siteurl="$(snapctl get siteurl)"
        if [ -n "$siteurl" ]; then
	  export OVERWRITE_SETTING_Site_Url=$siteurl
	fi

        if ls $SNAP_COMMON/*.env >/dev/null 2>&1; then
          for filename in $SNAP_COMMON/*.env; do
            while read env_var; do
              export "$env_var"
            done < $filename
          done
        fi

	node $SNAP/main.js
}

sleep_time=5
try_times=0

function try_start {

        refreshing="$(snapctl get snap-refreshing)"
        if [ $refreshing == "true" ]; then
            exit 0
        fi

	search=$(ps --pid $(cat $SNAP_COMMON/mongod.pid) -o comm=)

	if [ $search ]
        	then
                	start_rocketchat
        	else
			if [[ "$try_times" == 5 || "$try_times" > 5 ]]; then
		                echo "Was unable to connect to Mongo.  Please make sure Mongo has started successfully: sudo systemctl status snap.rocketchat-server.rocketchat-mongo to view logs: sudo journalctl -u snap.rocketchat-server.rocketchat-mongo"
               			exit 1;
        		fi

			((try_times += 1))
			((sleep_time += 5))
                	echo "Mongo is not available, can't start. Waiting ${sleep_time} seconds and trying again"
			sleep $sleep_time
			try_start
	fi
}

try_start
