#!/bin/sh

# Find all non-generated files that are python sources and need
# modification to support Python3.
list_python_sources () {
  git grep -l '^#!/usr/bin/env python' \
  | sed -e '/\.py$/d'
  git ls-tree -r --name-only HEAD \
  | sed -n \
    -e '/\.py$/p'
}

list_python_sources \
  | xargs 2to3 -w --no-diffs \
  > 23o 2>&1
sed -i -e '1i\
2to3: unmodified 2to3 output\
' 23o
git commit -F 23o -a

(
  # Edit sources for changes not handled by 2to3
  list_python_sources \
    | xargs sed -i -r \
        -e '\%^#!/usr/bin/env%s/python$/python3/' \
        -e '/#!python3>!/,/#!python3<!/d' \
        -e '/#!python3!/d' \
        -e 's@^#python3:@@' \
        -e 's@pyxb.utils.str@pyxb.utils.unicode@g' \
        -e '/#python3:int:long/s@\bint\b@long@g' \
        -e 's@^import StringIO@import io@' \
        -e 's@StringIO.StringIO@io.StringIO@g' \
        ;
  sed -i -r \
    -e '/_str_from_unicode/d' \
    -e 's/\b__unicode__\b/__str__/g' \
    -e '${/^$/d;}' \
    pyxb/exceptions_.py
  # Fix up references to python executable in shell scripts
  (
    git grep -lw python maintainer \
    | sed \
      -e '/2to3$/d'
    git ls-tree -r --name-only HEAD \
    | sed -n \
      -e '/\.sh$/p'
  ) | xargs sed -i -r \
        -e 's/\spython\b/&3/g' \
        -e 's/^python\b/&3/g'
) > edit 2>&1
git commit -a -m '2to3: automated edits'
