#!/bin/sh
# Script to upgrade to a new Qt.
# Apply VERY carefully, step by step.
#
# David Faure <faure@kde.org>
#

if test -z "$1"; then echo give snapshot file name; exit 1; fi
SNAPSHOT=$1

if [ ! -f $SNAPSHOT ]; then echo $SNAPSHOT not found ; fi

TOPLEVEL=`tar tf $SNAPSHOT | head -1 | sed -e 's,/$,,' `

echo Found TOPLEVEL=$TOPLEVEL

echo -n Cleaning qt-copy...
# Do a make svn-clean first
if [ ! -d qt-copy ]; then echo You should have a qt-copy directory under here ; fi
cd qt-copy
common="`which svn-clean`"
if [ -f ../kdesdk/scripts/svn-clean ] ; then common=../kdesdk/scripts/svn-clean; fi
if [ -f ../../kdesdk/scripts/svn-clean ] ; then common=../../kdesdk/scripts/svn-clean; fi
if [ -z "$common" ]; then
  echo svn-clean not found ;
else
  perl $common
fi
cd ..
echo done

# List of new stuff
echo -n Creating to_add and to_remove...
tar tf $SNAPSHOT | sort > qtlist     || exit 1
perl -pi -e "s/$TOPLEVEL/qt-copy/" qtlist

# Plus stuff we added ourselves
echo qt-copy/README.qt-copy >> qtlist
echo qt-copy/apply_patches >> qtlist
echo qt-copy/switch-qt-symlinks >> qtlist
echo qt-copy/upgrade_script.qt >> qtlist

tar tvf $SNAPSHOT | grep ' -> ' | sed -e "s, ->.*\$,,; s,^.*$TOPLEVEL/,qt-copy/," | sort -u > new_links
changed_links=
find qt-copy -type l -print | sort -u > old_links

for link in `cat new_links`; do
  if test -f $link; then 
    changed_links="$changed_links $link"
  fi
done
for link in `cat old_links`; do
  if ! grep -q $link new_links; then
    changed_links="$changed_links $link"
  fi
done

# Prepare list of what's new 
: > to_add
cat qtlist | while read a ; do
  if [ ! -e "$a" ]; then
     echo "$a" >> to_add
  fi
done
for a in $changed_links; do echo $a >> to_add; done

# And what we don't want to see in our svn
perl -pi -e 'if (/^qt-copy\/src\/tools\/qmodules.h/) {$_ = "";}' to_add

# Remove old stuff
: > to_remove
find qt-copy | grep -v .svn | grep -v debian | grep -v patches | while read a ; do
  if ! grep -q -F $a qtlist; then
    echo $a >> to_remove
  fi
done
echo done
for a in $changed_links; do echo $a >> to_remove; done

if [ ! -d qt-copy ]; then echo You should have a qt-copy directory under here ; fi # Better very safe than very sorry...
cd qt-copy
perl -pi -e "s/qt-copy\///" ../to_remove

cat ../to_remove | while read a; do
  echo Removing $a
  svn rm --force $a
done

cd ..

# Untar
echo -n Untarring snapshot over qt-copy...
rm -rf $TOPLEVEL
mv qt-copy $TOPLEVEL
tar xf $SNAPSHOT
mv $TOPLEVEL qt-copy
echo done

cd qt-copy
perl -pi -e "s/^.*qt-copy\///" ../to_add

cat ../to_add | while read a ; do
     echo Adding $a
     svn add $a
done

tar tf ../$SNAPSHOT | sort > ../qtlist || exit 1
perl -pi -e "s/$TOPLEVEL/qt-copy/" ../qtlist
# defang $Id$ tags
cat ../qtlist | while read a ; do
     if ! test -L ../$a && test -f ../$a; then
         perl -pi -e 's/<!-- \/\S+\/qt-x11-opensource-\S+ -->//' ../$a
     fi
done

echo done, please update README.qt-copy now
