#!/bin/sh

while getopts "a:" opt; do
  case $opt in
    a)
      ssh_alias=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

# Check if the alias is not empty
if [  -z "$ssh_alias" ]; then
  echo "\033[31mPlease input an ssh alias. Usage: first_deploy.sh -a {ssh_alias}"
  exit 1
fi

# Check if the build exists
if [ ! -f "build/out/distribution/qfixpt.gz" ]; then
  echo "\033[31mFile build/out/distribution/qfixpt.gz does not exist. Run make build"
  exit 1
fi

# Create the service
scp tools/qfixpt.service "$ssh_alias":/lib/systemd/system/

# Create folder just in case
ssh "$ssh_alias" "systemctl daemon-reload;systemctl enable qfixpt.service;systemctl start qfixpt.service;mkdir -p /home/quantex/qfixpt"

# Create start, stop and restart scripts
scp tools/start "$ssh_alias":/home/quantex/qfixpt/
scp tools/stop "$ssh_alias":/home/quantex/qfixpt/
scp tools/restart "$ssh_alias":/home/quantex/qfixpt/

# Copy zipped binary
scp build/out/distribution/qfixpt.gz "$ssh_alias":/home/quantex/qfixpt/
scp tools/unzip-qfixpt.sh "$ssh_alias":/home/quantex/qfixpt/

# Unzip the binary. Then systemd restart it automatically on file change.
ssh "$ssh_alias" "chown quantex:quantex -R /home/quantex/qfixpt;chmod +x /home/quantex/qfixpt/unzip-qfixpt.sh; /home/quantex/qfixpt/unzip-qfixpt.sh"
