#!/usr/bin/env bash
# Copyright (c) 2026 K2Aley. GAR-BOT. All rights reserved.
set -euo pipefail

BOOT_PATH="${1:-}"
USERNAME="${2:-garbot}"

if [[ -z "$BOOT_PATH" ]]; then
  echo "Usage: $0 /path/to/pi/bootfs [username]"
  echo "Example: $0 /Volumes/bootfs garbot"
  exit 1
fi

if [[ ! -d "$BOOT_PATH" ]]; then
  echo "Boot path not found: $BOOT_PATH"
  exit 1
fi

touch "$BOOT_PATH/ssh"

if ! command -v openssl >/dev/null 2>&1; then
  echo "Created $BOOT_PATH/ssh"
  echo "openssl was not found, so userconf.txt was not created."
  echo "Use Raspberry Pi Imager to set the Pi username/password, then boot the card."
  exit 0
fi

read -r -s -p "Password for $USERNAME: " PASSWORD
echo

HASH="$(openssl passwd -6 "$PASSWORD")"
printf "%s:%s\n" "$USERNAME" "$HASH" > "$BOOT_PATH/userconf.txt"

echo "Created $BOOT_PATH/ssh"
echo "Created $BOOT_PATH/userconf.txt for user '$USERNAME'"
echo "Boot the Pi, then connect with:"
echo "ssh $USERNAME@192.168.0.161"
