#!/bin/bash

set -euo pipefail

YAML_FILE="access.yml"
TEMPLATE_FILE="gitconfig.template"
USER="$1"

# Extract user fields from YAML
GIT_NAME=$(yq ".\"$USER\".name" "$YAML_FILE")
GIT_EMAIL=$(yq ".\"$USER\".email" "$YAML_FILE")

# Ensure fields are not empty
if [[ -z "$GIT_NAME" || -z "$GIT_EMAIL" ]]; then
  echo "❌ Error: User '$USER' not found or missing name/email in $YAML_FILE"
  exit 1
fi

# Create output directory
USER_DIR="files/$USER"
mkdir -p "$USER_DIR"

# Generate .gitconfig
env GIT_NAME="$GIT_NAME" GIT_EMAIL="$GIT_EMAIL" \
  envsubst <"$TEMPLATE_FILE" >"$USER_DIR/gitconfig"

echo "✅ .gitconfig created at $USER_DIR/gitconfig"

# Generate SSH keypair if it doesn't exist
KEYFILE="$USER_DIR/id_ed25519"

if [[ -f "$KEYFILE" ]]; then
  echo "🔑 SSH key already exists for $USER at $KEYFILE"
else
  ssh-keygen -t ed25519 -N "" -C "$GIT_EMAIL" -f "$KEYFILE"
  echo "✅ SSH keypair generated at:"
  echo "   🔐 Private: $KEYFILE"
  echo "   🔓 Public : $KEYFILE.pub"
fi
