#!/bin/bash

serviceLocation=$1
serviceName="io.techmine.techmine"
backupLocation="./serviceBackup"
latestServiceLocation="./latestService"

service=$(launchctl list | grep $serviceName)
INSTALLER_USER=$2
if [ -d "$backupLocation" ]; then
    rm -rf "$backupLocation"
fi
if [ "$service" = -* ]; then
    echo "The Service Is Not Running" >&2
else
    launchctl stop $serviceName
    mv "$serviceLocation" "$backupLocation"
    mv "$latestServiceLocation" "$serviceLocation"
    sed -i '' "s/{User}/${INSTALLER_USER}/g" /Applications/TechMine.app/Contents/Resources/io.techmine.techmine.plist
    launchctl start $serviceName

    if [ "$service" = -* ]; then
        if [ -d "$backupLocation" ]; then
            mv "$serviceLocation" "$latestServiceLocation"
            mv "$backupLocation" "$serviceLocation"
            sed -i '' "s/{User}/${INSTALLER_USER}/g" /Applications/TechMine.app/Contents/Resources/io.techmine.techmine.plist
            launchctl start $serviceName
        else
            sed -i '' "s/{User}/${INSTALLER_USER}/g" /Applications/TechMine.app/Contents/Resources/io.techmine.techmine.plist
            launchctl start $serviceName
        fi
    fi
fi