#!/bin/bash

source /opt/scripts_local/shared_functions.sh

HOSTNAME=$(hostname)
TS_IP=$(tailscale ip -4)

# Install NodeJS
PACKAGE_NAME=install_nodejs.sh
install_package $PACKAGE_NAME

# Install cloudcmd
sudo npm i cloudcmd -g
if ! (sudo grep tc-$HOSTNAME /etc/caddy/Caddyfile >/dev/null 2>&1); then
  sudo bash -c "cat >> '/etc/caddy/Caddyfile'" << EOF
tc-$HOSTNAME.noxs.me:80 {
reverse_proxy $TS_IP:8000
}
EOF
  # Install cloudcmd config file
  SRC_FILE=config.json
  SRC_PATH=/mnt/union/shared/cloudcmd/$SRC_FILE
  DST_PATH=/lib/node_modules/cloudcmd/json/
  if [ "$HOSTNAME" == "vmx-nas" ]; then
    rsync -avP "$SRC_PATH" "$DST_PATH"/
  else
    rsync -avP -e "ssh -o StrictHostKeyChecking=no" root@vmx-nas.swallow-grue.ts.net:"$SRC_PATH" "$DST_PATH"
  fi
  sudo sed -i "s|XXX.XXX.XXX.XXX|$TS_IP|g" "$DST_PATH"/"$SRC_FILE"
  # Install cloudcmd service file
  SRC_FILE=cloudcmd.service
  SRC_PATH=/mnt/union/shared/cloudcmd/$SRC_FILE
  DST_PATH=/etc/systemd/system
  if [ "$HOSTNAME" == "vmx-nas" ]; then
    rsync -avP "$SRC_PATH" "$DST_PATH"/
  else
    rsync -avP -e "ssh -o StrictHostKeyChecking=no" root@vmx-nas.swallow-grue.ts.net:"$SRC_PATH" "$DST_PATH"
  fi
  sudo systemctl daemon-reload
  sudo systemctl enable now
  sudo systemctl reload caddy
fi
