#!/bin/bash

# TRee Installation Generator (TRIG)
# Copyright (C) 2014, Andrey Vladimirov

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


record() {
    C=0;
    while read F; do
	let C=C+1
	S=`realpath -s $F` # Full path
	D=${S#$R} # Path relative to the root of the tree
	if [ -h $S ]; then
	    # Processing symlink $S
	    L=`readlink $S` # Where $S is pointing to
	    echo "ln -s \"$L\" \"$D\"" >> $IF
	    echo "unlink \"$D\"" >> $TF
	elif [ -d $S ]; then
	    # Processing directory $D
	    if [ ! -d $D ]; then
		echo "mkdir -p \"$D\"" >> $IF
		echo "rmdir \"$D\"" >> $TF
	    fi
	else
	    # Processing regular file $D
	    if [ ! -e $D ]; then
		echo "install \"$S\" \"$D\"" >> $IF
		echo "rm -f \"$D\"" >> $TF
	    else
		echo "File \"$D\" already exists, skipping"
	    fi
	fi
    done
}


if [ $# -lt 1 ]; then
    echo "
TRIG, the TRee Installation Generator, Version 0.1

Usage: 
       `basename $0` /path/to/tree/ROOT

This will create two scripts: tree-install-ROOT.sh and tree-uninstall-ROOT.sh,
which contain commands for installing and uninstalling the files inside of
a regular directory ROOT/ into the root of the file system. 

For example, if /home/user/MyProg contains /home/user/MyProg/usr/bin/MyExec,
then running \"trig.sh /home/user/MyProg\" will create scripts that
copy/remove /home/user/MyProg/usr/bin/MyExec as /usr/bin/MyExec.
The scripts will be called tree-install-MyProg.sh and tree-uninstall-MyProg.sh.
They will be located one level above MyProg, i.e., in /home/user/.

TRIG is useful, for example, for installing unpacked and modified RPMs 
in RHEL-like Linux operating systems.
"
    
    exit 1
fi

if [ ! -d $1 ]; then
    echo "Directory $1 does not exist or is not a directory"
    exit 2
fi

R=`realpath $1` # Full path to the tree

cd $R/.. # Go one level up
B=`basename $R` # Name of the tree
IF=tree-install-${B}.sh # Install file
UF=tree-uninstall-${B}.sh # Uninstall file
TF=tree-uninstall-${B}-tmp.sh # Uninstall file (temporary)

echo "Creating $IF to install the tree of files in $R into /"
echo "Creating $UF to uninstall files installed by $IF"

echo '#!/bin/bash' > $IF
echo '#!/bin/bash' > $UF

find $R/ | record # Process all files inside of the tree

cat $TF | tac >> $UF # Uninstallation must proceed in reverse order
rm -f $TF

chmod +x $IF
chmod +x $UF

