#!/usr/bin/env bash
set -euo pipefail
host="${LAPTOP_HOST:-brag-pipe-fur-kneel.emperor-ratio.ts.net}"
port="${LAPTOP_PORT:-2222}"
key="${LAPTOP_SSH_KEY:-$HOME/.ssh/id_ed25519_laptop_agent}"
ssh_opts=(-p "$port" -o BatchMode=yes -o IdentitiesOnly=yes)
scp_opts=(-P "$port" -o BatchMode=yes -o IdentitiesOnly=yes)
if [[ -f "$key" ]]; then
  ssh_opts+=( -i "$key" )
  scp_opts+=( -i "$key" )
fi
usage() {
  echo "usage: laptop-write <remote-path>            # read stdin, write atomically on laptop" >&2
  echo "   or: laptop-write --from <local-file> <remote-path>" >&2
}
if [[ $# -lt 1 ]]; then
  usage
  exit 2
fi
src_mode="stdin"
local_file=""
if [[ "${1:-}" == "--from" ]]; then
  if [[ $# -ne 3 ]]; then
    usage
    exit 2
  fi
  src_mode="file"
  local_file="$2"
  remote_path="$3"
else
  if [[ $# -ne 1 ]]; then
    usage
    exit 2
  fi
  remote_path="$1"
fi
remote_dir=$(dirname "$remote_path")
remote_base=$(basename "$remote_path")
remote_tmp="${remote_dir}/.${remote_base}.tmp.$$"
ssh -n "${ssh_opts[@]}" "$host" "mkdir -p -- \"$remote_dir\""
if [[ "$src_mode" == "file" ]]; then
  scp "${scp_opts[@]}" -q "$local_file" "$host:$remote_tmp"
else
  ssh "${ssh_opts[@]}" "$host" "cat > \"$remote_tmp\""
fi
ssh -n "${ssh_opts[@]}" "$host" "mv -- \"$remote_tmp\" \"$remote_path\""
