#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<EOF
Usage: $0 [-p port] user@host

Example:
  $0 sunrise@192.168.10.210
  $0 -p 2222 sunrise@192.168.10.210

This script creates an SSH key pair if needed and installs the public key on the remote host,
so you can log in without a password.
EOF
}

PORT=22
while getopts ":p:" opt; do
  case "$opt" in
    p) PORT="$OPTARG" ;;
    *) usage; exit 1 ;;
  esac
done
shift $((OPTIND - 1))

if [ $# -ne 1 ]; then
  usage
  exit 1
fi

REMOTE="$1"

if ! command -v ssh >/dev/null 2>&1; then
  echo "Error: ssh command not found." >&2
  exit 1
fi

if [ -z "${SSH_AUTH_SOCK:-}" ]; then
  echo "Warning: SSH agent is not running. You can still use ssh-keygen and ssh-copy-id."
fi

KEYFILE="$HOME/.ssh/id_rsa"
PUBKEYFILE="$KEYFILE.pub"

if [ ! -f "$KEYFILE" ] || [ ! -f "$PUBKEYFILE" ]; then
  echo "SSH key pair not found. Generating a new key at $KEYFILE..."
  mkdir -p "$HOME/.ssh"
  chmod 700 "$HOME/.ssh"
  ssh-keygen -t rsa -b 4096 -f "$KEYFILE" -N "" -C "${USER:-$(whoami)}@$(hostname)"
else
  echo "Found existing SSH key: $KEYFILE"
fi

SSH_OPTS=(-p "$PORT")
if command -v ssh-copy-id >/dev/null 2>&1; then
  echo "Installing public key on remote host using ssh-copy-id..."
  ssh-copy-id "${SSH_OPTS[@]}" "$REMOTE"
else
  echo "ssh-copy-id not found, using manual upload..."
  mkdir -p "$HOME/.ssh"
  chmod 700 "$HOME/.ssh"
  cat "$PUBKEYFILE" | ssh "${SSH_OPTS[@]}" "$REMOTE" 'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'
fi

echo "Testing passwordless login to $REMOTE..."
ssh -o BatchMode=yes "${SSH_OPTS[@]}" "$REMOTE" exit

if [ $? -eq 0 ]; then
  echo "Success: passwordless SSH login is configured for $REMOTE"
  echo "You can now connect with: ssh ${SSH_OPTS[*]} $REMOTE"
else
  echo "Warning: passwordless SSH login may not be configured correctly." >&2
  exit 1
fi
