#!/bin/bash

source /opt/scripts_local/shared_functions.sh

if ! (sudo systemctl status | grep [c]loudcmd>/dev/null 2>&1); then 
  TS_IP=$(sudo tailscale ip -4)
  curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
  sudo apt install nodejs
  sudo npm i cloudcmd -g
sudo bash -c "cat > '/etc/systemd/system/cloudcmd.service'" << EOF
[Unit]
Description=Cloud Commander
After=network.target
[Service]
TimeoutStartSec=0
Restart=always
User=root
ExecStart=/lib/node_modules/cloudcmd/bin/cloudcmd.mjs
[Install]
WantedBy=multi-user.target
EOF
  sudo systemctl daemon-reload
  sudo systemctl enable --now cloudcmd
  sudo sed -i "s|null|$TS_IP|g" /lib/node_modules/cloudcmd/json/config.json
  sudo systemctl daemon-reload
  sudo systemctl enable --now cloudcmd
  if ! (sudo grep tc- /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
  sudo systemctl reload caddy
  fi
else
  echo "Cloudcmd already installed! exiting..." 
fi
