#!/usr/bin/env bash
# Tecqify machine fix: SSH for Coolify + always-on + Wake-on-LAN. Safe to re-run.
set -e
# usage: wget -qO- fix.tecqify.com | sudo bash -s <name>   (name optional, e.g. g3080)
[ "$(id -u)" = 0 ] || { echo "Run with sudo: wget -qO- fix.tecqify.com | sudo bash -s <name>"; exit 1; }
NAME="${1:-}"
export DEBIAN_FRONTEND=noninteractive
echo "==> Installing basics"
apt-get update -qq && apt-get install -y -qq curl wget ca-certificates gnupg lsb-release openssh-server ethtool wakeonlan pciutils >/dev/null
if ! command -v tailscale >/dev/null; then
  echo "==> Installing Tailscale"
  curl -fsSL https://tailscale.com/install.sh | sh
fi
systemctl enable --now tailscaled >/dev/null 2>&1 || true
if ! tailscale ip -4 >/dev/null 2>&1; then
  echo "==> Joining Tailscale: open the login link below and sign in with businesspilot.care@gmail.com"
  tailscale up ${NAME:+--hostname=$NAME}
elif [ -n "$NAME" ]; then tailscale set --hostname="$NAME" || true; fi
echo "==> SSH: normal sshd (Tailscale SSH off)"
command -v tailscale >/dev/null && tailscale set --ssh=false || true
systemctl enable --now ssh >/dev/null 2>&1 || systemctl enable --now sshd >/dev/null 2>&1 || true
systemctl enable --now tailscaled >/dev/null 2>&1 || true
KEY='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINuzGG0vXvVWAEku7b9ztYyIGKukcdEt7eir8303fm2G coolify'
mkdir -p /root/.ssh && chmod 700 /root/.ssh && touch /root/.ssh/authorized_keys
grep -qF "$KEY" /root/.ssh/authorized_keys || echo "$KEY" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
echo "==> Always on: no sleep"
systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target >/dev/null 2>&1 || true
mkdir -p /etc/systemd/logind.conf.d
printf '[Login]\nHandleLidSwitch=ignore\nHandleLidSwitchExternalPower=ignore\nHandleSuspendKey=ignore\nIdleAction=ignore\n' > /etc/systemd/logind.conf.d/no-sleep.conf
echo "==> Wake-on-LAN on wired ports"
cat > /etc/systemd/system/wol@.service <<'U'
[Unit]
Description=Wake-on-LAN for %i
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/sbin/ethtool -s %i wol g
[Install]
WantedBy=multi-user.target
U
systemctl daemon-reload
for n in /sys/class/net/*; do i=$(basename "$n"); [ -e "$n/device" ] && [ ! -d "$n/wireless" ] || continue
  ethtool -s "$i" wol g 2>/dev/null && systemctl enable "wol@$i" >/dev/null 2>&1 && echo "   WoL on $i ($(cat $n/address))" || echo "   $i: WoL not supported"; done
command -v nvidia-smi >/dev/null && nvidia-smi --query-gpu=name,memory.total --format=csv,noheader || lspci | grep -iE "vga|3d" || true
echo; echo "DONE on $(hostname) - $(lsb_release -ds 2>/dev/null)"
echo "Tailscale IP: $(tailscale ip -4 2>/dev/null | head -1)"
ip -br link | grep -v '^lo'
echo "Now: BIOS 'Restore on AC Power Loss' = Power On + enable Wake on LAN; Tailscale admin > Disable key expiry."
