#!/usr/bin/env bash
# Enter share credentials interactively and write them to their target files.
# Nothing secret is stored in the repo or on external media — you type it in here.
# Mount points + fstab entries are handled by 02-system/60-shares.sh, not this script.
#   sudo ./run.sh
set -euo pipefail
[ "$(id -u)" -eq 0 ] || { echo "run as root (writes /etc/*)"; exit 1; }

ask()  { local v; read -rp "  $1: " v;  printf '%s' "$v"; }           # visible
asks() { local v; read -rsp "  $1: " v; echo >&2; printf '%s' "$v"; } # hidden

# --- CIFS //nase.meow/data -> /etc/nase.meow.credentials ---
echo "nase.meow (CIFS) credentials:"
nm_user="$(ask username)"
nm_pass="$(asks password)"
nm_dom="$(ask 'domain (blank = none)')"
{
  printf 'username=%s\npassword=%s\n' "$nm_user" "$nm_pass"
  if [ -n "$nm_dom" ]; then printf 'domain=%s\n' "$nm_dom"; fi
} | install -Dm600 /dev/stdin /etc/nase.meow.credentials
echo "  wrote /etc/nase.meow.credentials (600)"

# --- davfs https://files.70b1.de -> /etc/davfs2/secrets ---
# Format: <resource> <username> <password>, one per line. We replace only this
# resource's line, leaving any other davfs secrets intact.
echo "files.70b1.de (davfs) credentials:"
dv_user="$(ask username)"
dv_pass="$(asks password)"
res="https://files.70b1.de"
tmp="$(mktemp)"
grep -vE "^${res//./\\.}[[:space:]]" /etc/davfs2/secrets 2>/dev/null > "$tmp" || true
printf '%s %s %s\n' "$res" "$dv_user" "$dv_pass" >> "$tmp"
install -Dm600 "$tmp" /etc/davfs2/secrets && rm -f "$tmp"
echo "  wrote /etc/davfs2/secrets (600)"

echo "credentials written. Mount with 'mount -a' or reboot (mounts wait on the -ready services)."
