#!/usr/bin/env bash
# Usage: fix-perms.sh [-o owner[:group]] <directory>
# Example: fix-perms.sh -o vaultwarden /srv/vaultwarden
#          fix-perms.sh -o vaultwarden:vaultwarden /srv/vaultwarden

set -euo pipefail

# require root
if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root." >&2
  exit 1
fi

OWNER=""
TARGET=""

# Parse arguments
while [[ $# -gt 0 ]]; do
  case "$1" in
    -m|--media)
      OWNER=":media"
      shift
      ;;
    -o|--owner)
      OWNER="$2"
      shift 2
      ;;
    -*)
      echo "unknown option: $1"
      exit 1
      ;;
    *)
      TARGET="$1"
      shift
      ;;
  esac
done

if [[ -z "$TARGET" ]]; then
  echo "usage: $0 [-o owner[:group]] <directory>"
  exit 1
fi

if [[ ! -d "$TARGET" ]]; then
  echo "error: '$TARGET' is not a directory"
  exit 1
fi

echo "======================================"
echo "Target directory:  $TARGET"
if [[ -n "$OWNER" ]]; then
  echo "Ownership change:  $OWNER"
else
  echo "Ownership change:  (none)"
fi
echo "Directory perms:   2770 (setgid)"
echo "File perms:        660"
echo "======================================"
read -rp "Proceed with these changes? [y/N]: " CONFIRM

if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
  echo "Aborted."
  exit 0
fi

echo "setting permissions under: $TARGET"

# optionally change ownership
if [[ -n "$OWNER" ]]; then
  echo "changing ownership to: $OWNER"
  sudo chown -R "$OWNER" "$TARGET"
fi

# Set permissions for directories (with setgid)
find "$TARGET" -type d -exec chmod 2770 {} +

# Set permissions for files
find "$TARGET" -type f -exec chmod 660 {} +

echo "fin"

