#!/bin/bash

#  Install.sh
#  Remoto
#
#  Created by Matius on 5/12/2022.
#

#echo "$1" > /Users/mac/Desktop/working

bundlePath="$1";
applicationSupport="/Library/Application Support/com.macremoto";
daemonInstallPath="/Library/LaunchDaemons";
resourcesPath="$bundlePath/Contents/Resources/Install";
binaryPath="/usr/local/bin/remoto"

sudo mkdir -p "$applicationSupport";
sudo mkdir -p "/usr/local/bin";

sudo launchctl unload -w "$daemonInstallPath/"com.macremoto*;

sudo cp "$bundlePath/Contents/MacOS/RemotoDaemon" "$binaryPath";
sudo cp "$resourcesPath/"com.macremoto* "$daemonInstallPath"
sudo chown root "$daemonInstallPath/"com.macremoto*;

sudo chmod 777 "$binaryPath";
sudo xattr -d com.apple.quarantine "$binaryPath";
sudo spctl --add "$binaryPath";
sudo chmod u+x "$binaryPath";

sudo cp "$resourcesPath/server.key" "$applicationSupport"
sudo cp "$resourcesPath/secure.crt" "$applicationSupport"

sudo chmod 600 "$applicationSupport/server.key"
sudo chmod 777 "$applicationSupport/secure.crt"

sudo security verify-cert -c "$resourcesPath/secure.crt" > /dev/null 2>&1;
if [ \$? != 0 ]; then
    sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$resourcesPath/secure.crt";
fi

sudo launchctl load -w "$daemonInstallPath/"com.macremoto*;

systemsetup -setremotelogin on; dseditgroup -o delete com.apple.access_ssh; /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -clientopts -setreqperm -reqperm yes -activate -configure -privs -all -allowAccessFor -allUsers -restart -agent
