40990bb
#!/bin/bash -eu
257a3a9
257a3a9
# If using normal root, avoid changing anything.
257a3a9
if [ -z "$RPM_BUILD_ROOT" -o "$RPM_BUILD_ROOT" = "/" ]; then
257a3a9
  exit 0
257a3a9
fi
257a3a9
fb05a23
exclude_files="${1:-}"
fb05a23
exclude_shebangs="${2:-}"
fb05a23
257a3a9
cd "$RPM_BUILD_ROOT"
257a3a9
257a3a9
trim() {
257a3a9
  printf '%s' "$*"
257a3a9
}
257a3a9
257a3a9
fail=0
40990bb
while IFS= read -r -d $'\0' f; do
40990bb
  file -N --mime-type "$f" | grep -q -P ".+(?=: text/)" || continue
257a3a9
fb05a23
  # Remove the dot
fb05a23
  path="${f#.}"
fb05a23
fb05a23
  if [ -n "$exclude_files" ]; then
fb05a23
    echo "$path" | grep -q -E "$exclude_files" && continue
fb05a23
  fi
fb05a23
257a3a9
  ts=$(stat -c %y "$f")
257a3a9
8f59b75
  read shebang_line < "$f" || :
8f59b75
  orig_shebang=$(trim $(echo "$shebang_line" | grep -Po "#!\K.*" || echo))
8f59b75
  shebang="$orig_shebang"
fb05a23
  if [ -n "$exclude_shebangs" ]; then
fb05a23
    echo "$shebang" | grep -q -E "$exclude_shebangs" && continue
fb05a23
  fi
fb05a23
257a3a9
  if [ -z "$shebang" ]; then
257a3a9
    echo >&2 "*** WARNING: $f is executable but has empty or no shebang, removing executable bit"
257a3a9
    chmod -x "$f"
257a3a9
    touch -d "$ts" "$f"
257a3a9
    continue
51f1c66
  elif [ -n "${shebang##/*}" ]; then
257a3a9
    echo >&2 "*** ERROR: $f has shebang which doesn't start with '/' ($shebang)"
257a3a9
    fail=1
257a3a9
    continue
257a3a9
  fi
257a3a9
257a3a9
  if ! { echo "$shebang" | grep -q -P "^/(?:usr/)?(?:bin|sbin)/"; }; then
257a3a9
    continue
257a3a9
  fi
257a3a9
257a3a9
  # Replace "special" env shebang:
35f7182
  # /whatsoever/env /whatever/foo → /whatever/foo
35f7182
  shebang=$(echo "$shebang" | sed -r -e 's@^(.+)/env /(.+)$@/\2@')
257a3a9
  # /whatsoever/env foo → /whatsoever/foo
257a3a9
  shebang=$(echo "$shebang" | sed -r -e 's@^(.+/)env (.+)$@\1\2@')
257a3a9
257a3a9
  # Replace ambiguous python with python2
257a3a9
  py_shebang=$(echo "$shebang" | sed -r -e 's@/usr/bin/python(\s|$)@/usr/bin/python2\1@')
257a3a9
257a3a9
  if [ "$shebang" != "$py_shebang" ]; then
257a3a9
    sed -i -e "1c #!$py_shebang" "$f"
8f59b75
    echo >&2 "*** WARNING: mangling shebang in $path from #!$orig_shebang to #!$py_shebang. This will become an ERROR, fix it manually!"
8f59b75
  elif [ "#!$shebang" != "#!$orig_shebang" ]; then
257a3a9
    sed -i -e "1c #!$shebang" "$f"
fb05a23
    echo "mangling shebang in $path from $orig_shebang to #!$shebang"
257a3a9
  fi
257a3a9
257a3a9
  touch -d "$ts" "$f"
40990bb
done < <(find -executable -type f -print0)
257a3a9
257a3a9
exit $fail