#!/bin/sh -e
#
# wifi-passwords - get plaintext saved wifi passwords

case "$(uname)" in
  Darwin)
    security find-generic-password -D "AirPort network password" -g -w
    exit 0
    ;;
  *)
    if command -v nmcli >/dev/null 2>&1; then
      connection="$(nmcli connection show --active | grep wifi | head -n 1)"
      # first column
      connection_name="${connection%% *}"
      [ -z "${connection_name}" ] && exit 1

      secret="$(nmcli connection show --show-secrets "${connection_name}" | grep psk:)"
      # last column
      echo "${secret##* }"
      exit 0
    fi
    if [ -d /etc/NetworkManager/system-connections/ ]; then
      sudo grep -H '^psk=' /etc/NetworkManager/system-connections/*
    fi
    ;;
esac
