#!/bin/bash

# puede ser sudo, ejecutado por un paquete para todos los usuario
# o ser llamada por un usuario que quiere instalarlo en su espacio

######################################################################################

PROG=installuserfiles
USER=$1
PACK=$2
PREFIX=$3

if test x"$1" = x--help ; then
    echo $PROG-$PACK parte de las post de deb y rpm
    echo a partir de dirac
    exit 0
    fi

if test x"$1" = x--version ; then
    echo $PROG-$PACK
    echo a 
    exit 0
    fi

function installuserfilesfun {
### si el usuario es root no hay /home/root, ademas no INSTALAR AL ROOT
 

USER=$1
PACK=$2
PREFIX=$3   # ojo si es /home le sumo user

if test x"$PREFIX" = x/home ; then
    PREFIX=/home/$USER
    fi
    
 
SHAREDIR="$PREFIX/share/$PACK"
if test ! -d $SHAREDIR ; then 
    echo $PACK no está instalado
    exit;
    fi

USERID=`grep "^$USER:" /etc/passwd| awk -F':' '{print $3}'`;

#USERACTUAL=`id -un`
EXEUSERID=`id -u`;

# revisar el papel de xdg???
if test x"$EXEUSERID" = x0 ||  x"$EXEUSERID" != x"$USERID"; then
                 for DF in $SHAREDIR/launchers/* ; do
	             echo "su $USER -c xdg-desktop-icon install $DF";
	             su $USER -c "xdg-desktop-icon install $DF";
		 done;
		 # no entiendo que hace cdg??
	         if test -d /home/$USER/Escritorio ; then 
                     echo  su $USER -c cp $SHAREDIR/launchers/* /home/$USER/Escritorio;
	             su $USER -c "cp  $SHAREDIR/launchers/* /home/$USER/Escritorio" ;
		     su $USER -c  "sed -i 's/\/usr\/local/$PREFIX/g' $SHAREDIR/launchers/*"
	             fi; 
		 su $USER -c "mkdir -p /home/$USER/$PACK_ejemplos"; 
		 su $USER -c "cp -r ${SHAREDIR}/examples/* /home/$USER/$PACK_ejemplos";  
		 #chown -R $USER /home/$$USER/$PACK_ejemplos;
elif  test x"$EXEUSERID" = x"$USERID" ; then
                 for DF in $SHAREDIR/launchers/* ; do
	             echo "xdg-desktop-icon install $DF";
	             xdg-desktop-icon install $DF;
		 done;
	         if test -d /home/$USER/Escritorio ; then 
                     echo  cp  $SHAREDIR/launchers/* /home/$USER/Escritorio;
	             cp  $SHAREDIR/launchers/* /home/$USER/Escritorio ;
		     sed -i 's/\/usr\/local/$PREFIX/g' $SHAREDIR/launchers/*
	         fi; 
		 mkdir -p /home/$USER/$PACK_ejemplos; 
		 cp -r ${SHAREDIR}/examples/* /home/$USER/$PACK_ejemplos;  
		 #chown -R $USER /home/$USER/$PACK_ejemplos;
else
    echo No soy ROOT -soy: USER $USER, UID: $EXEUSERID-   y se pretende instalar otro usuario, no puedo. 
		 
 fi
    
}
##################################################################################################


 installuserfilesfun  $USER $PACK $PREFIX
