#!/usr/bin/env bash

echoerr() { echo "$@" 1>&2; }

PWFILE="$HOME/.private/ansible/ansible-oopen-vault-passphrase"

if test ! -f "$PWFILE"
then
  echoerr "File doesn't exist!"
  exit 1
fi

perm=$(/bin/ls -l "$PWFILE" | awk '{print $1}')
owner=$(/bin/ls -l "$PWFILE" | awk '{print $3}')
group=$(/bin/ls -l "$PWFILE" | awk '{print $4}')
#not everyone is using debian based foo. get primary group of user and test file group permission against it
pgroup=$(id -gn)

if [[ "$perm" != "-rw-------" ]] && [[ "$perm" != "-r--------" ]]
then
  echoerr "Wrong permissions!"
  exit 1
fi

if test "$USER" != "$owner"
then
  echoerr "Wrong owner!"
  exit 1
fi

if test "$pgroup" != "$group"
then
  echoerr "Wrong group!"
  exit 1
fi

cat "$PWFILE"
exit 0
