#!/bin/sh

#######################################################################
#
# (C) 2006 Arnold Joseph Noronha
# This is free software. You are free to modify and/or redistribute this 
# under the terms of the GNU General Public License version 2 or above
#
########################################################################

prefix=~/.local/
pkg=$2

if ( echo $pkg | grep  ':' ) ; then
    pfile="${pkg##*/}"
    echo "Downloading to $pfile.";
    wget -c $pkg $pfile;
    $pkg = $pfile
fi

if ( echo $pkg | grep '/' ) ; then
    pfile="${pkg##*/}"
    cd /tmp
    cp $pkg $pfile
    pkg=$pfile
fi

cachedir=$prefix/local-cache/
cache=$cachedir/$pkg

action=$1
function getyesno () {
    local ans
    echo "$1 (yes/no) ? "
    ans=dumb
    while [ "$ans" != "yes" -a "$ans" != "no" ] ; do
	if [ "$ans" != "dumb" ]; then
	    echo "Enter yes or no: "
	fi
	read ans
    done
    if [ "$ans" == "yes" ]; then
	return 0
    fi
    return 1
}

    
if [ "$action" == "" -o "$pkg" == "" ] ; then
    echo "Usage: install-deb action <package-name>"
    echo "       Actions allowed: install remove"
    echo "       Actions without package name: list setup"
    exit 1
fi

if [ "$action" == "list" ] ; then
    ls -d $cachedir/*
    exit 0
fi
if [ "$action" == "remove" ] ; then
    #difficult work!
    if [ ! -d $cache ] ; then
	echo "No such package installed. Use install-deb list for package list"
	exit 1
    fi
    
    if ! ( getyesno  "$pkg will be removed" ) ; then
	exit 1
    fi

    for p in `cat $cache/info` ; do
	if [ -f $prefix/$p ] ; then
	    rm -vf $prefix/$p
	fi
    done
    rm -rf $cache
    exit 0
fi
      
    
if [ "$action" != "install" -o ! -f "$pkg" ]; then
    echo "install-deb: bad action or package does not exist"
    exit 1
fi

if [ ! -e $prefix ] ; then
    mkdir $prefix  
fi


if ! ( echo $PATH | grep -q "$prefix" ) ; then
    export PATH=$prefix:$PATH
    echo "export PATH=${prefix}/bin:\$PATH" >> ~/.bashrc
fi

if ! ( echo $LD_LIBRARY_PATH | grep -q $prefix  ) ; then
    export LD_LIBRARY_PATH=$prefix/lib
    echo "export LD_LIBRARY_PATH=$prefix/lib" >> ~/.bashrc
fi
  



if [ -e $cache ] ; then
    echo this program seems to have been installed earlier
    echo Please uninstall before trying to reinstall
    exit 1
fi

echo "Making cache dirs..."
mkdir $cachedir $cache

echo "Extracting package..."
dpkg-deb --extract $pkg $cache/

cd $cache

#make cache info
cd usr
find *  > $cache/info
cd ..

echo "Copying files..."
cp -vuaf $cache/usr/* $prefix
cp -vuaf $cache/lib/* $prefix/lib/
cp -vuaf $cache/etc/* $prefix/etc/

rm -rf $cache/usr

#TODO: if theres another other than usr give warning!











