#!/bin/sh

if [ $# != 2 ]; then
    echo "Usage: $0 old_classname new_classname"
    exit 1
fi

oldname=$1
newname=$2

if [ -f $oldname.cpp ]; then
    oldfile=$oldname
    newfile=$newname
else
    oldfile=`echo $oldname | tr A-Z a-z`
    newfile=`echo $newname | tr A-Z a-z`
fi

if [ ! -f $newfile.h ]; then
    echo "Copying $oldfile.{cpp,h} to $newfile.{cpp,h}"
    cp $oldfile.h $newfile.h
    cp $oldfile.cpp $newfile.cpp
    if [ -f ${oldfile}_p.h ]; then
        cp ${oldfile}_p.h ${newfile}_p.h
    fi
    if [ -f ${oldfile}.ui ]; then
        echo "Copying $oldfile.ui to $newfile.ui"
        cp ${oldfile}.ui ${newfile}.ui
    fi

    git add $newfile.h
    git add $newfile.cpp
    if [ -f ${newfile}_p.h ]; then
        git add ${newfile}_p.h
    fi
    if [ -f ${newfile}.ui ]; then
        git add ${newfile}.ui
    fi
fi

# Update build system
if test -f CMakeLists.txt; then
    buildsystemfile=CMakeLists.txt
    separator=
else
    buildsystemfile=`ls -1 *.pro 2>/dev/null | head -n 1`
    separator=' \\'
fi
if test -n "$buildsystemfile"; then
    perl -pi -e '$_ .= "$1'$newfile.cpp"$separator"'\n" if (m/^(\s*)'$oldfile'\.cpp/)' $buildsystemfile
    perl -pi -e '$_ .= "$1'$newfile.h"$separator"'\n" if (m/^(\s*)'$oldfile'\.h/)' $buildsystemfile
    perl -pi -e '$_ .= "$1'$newfile.ui"$separator"'\n" if (m/^(\s*)'$oldfile'\.ui/)' $buildsystemfile
fi

# Rename class
perl -pi -e "s/$oldname/$newname/g" $newfile.h $newfile.cpp
if [ -f ${newfile}_p.h ]; then
    perl -pi -e "s/$oldname/$newname/g" ${newfile}_p.h
fi
if [ -f ${newfile}.ui ]; then
    perl -pi -e "s/$oldname/$newname/g" ${newfile}.ui
fi

oldinclguard=`echo $oldname | tr a-z A-Z`
newinclguard=`echo $newname | tr a-z A-Z`

# Update include guard
perl -pi -e "s/$oldinclguard/$newinclguard/g" $newfile.h

# Update includes in cpp file
perl -pi -e 's/\b'$oldfile'\.h/'$newfile'\.h/' $newfile.cpp
perl -pi -e 's/\b'$oldfile'\.moc/'$newfile'\.moc/' $newfile.cpp
perl -pi -e 's/\b'moc_$oldfile'\.cpp/'moc_$newfile'\.cpp/' $newfile.cpp
