#!/bin/bash

#   -------------------------------------------------------------------
#
#   Shell program to set up Xubuntu 8.10 (i386) for use in internetcafes.
#
#   Copyright 2008, chirlu <chirlu@gmx.de>.
#
#   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.
#
#   Description:
#
#   NOTE: You must be the superuser to run this script.
#
#   Usage:
#
#       xubuntu-setup-script [ -h | --help ]
#
#   Options:
#
#       -h, --help    Display this help message and exit.
#
#
#   Revision History:
#
#   2008-05-08	0.0.1	File created by new_script ver. 2.1.0
#   2008-05-08	0.1.0	Basic coding and testing
#   2008-05-09	0.1.1	Improve interaction
#   2008-05-16	0.1.2	Added links, totem-xine external codecs, panel-items, 
#			sessions and startup settings
#   2008-07-23  0.1.3   Added automatic security updates and login without 
#                       password for the guests-account
#   2008-09-18  0.1.4   changed to aptitude, add sound-juicer & soundconverter,
#                       configure volmanrc
#   2008-12-08  0.2.0   update to 8.10, all used archives in 1 archive (folder),
#                       replaced pkg xubuntu-restricted-extras with single pkgs
#                       from xubuntu-restricted-extras hardy & intrepid
#   2009-03-02  0.2.1   added streamripper, permissions (groups) for new user
#                       autostart_volmanrc: use %d for device
#   2009-03-04  0.2.2   added /opt/restore-home, removed other homefolderconfigs
#   2009-05-05  0.3.0   update to 9.04: 
#                         replaced msttcorefonts with ttf-mscorefonts-installer
#                         replaced libdvdread3 with libdvdread4
#                         new re-home.tar.bz2
#                        removed autostart_volmanrc from script 
#                         (settings are in re-home.tar.bz2) 
#   -------------------------------------------------------------------


#   -------------------------------------------------------------------
#   Constants
#   -------------------------------------------------------------------

PROGNAME=$(basename $0)
PROGDIR=$(dirname $0)
VERSION="0.3.0"



#   -------------------------------------------------------------------
#   Functions
#   -------------------------------------------------------------------

function usage
{

#   -----------------------------------------------------------------------
#   Function to display usage message (does not exit)
#   -----------------------------------------------------------------------

echo "Usage: ${PROGNAME} [-h | --help]"
}


function helptext
{

#   -----------------------------------------------------------------------
#   Function to display help message for program
#   -----------------------------------------------------------------------

cat <<- -EOF-

${PROGNAME} ver. ${VERSION}
This is a program to set up Xubuntu 9.04 (i386) for use in internetcafes.

$(usage)

Options:

-h, --help    Display this help message and exit.

-EOF-
}



function error_exit
{

#   -----------------------------------------------------------------------
#   Function for exit due to fatal program error
#       Arguments:
#           1    string containing descriptive error message
#   -----------------------------------------------------------------------


echo "${PROGNAME}: ${1:-"Unknown Error"}" >&2
exit 1
}


function signal_exit
{

#   -----------------------------------------------------------------------
#   Function to handle termination signals
#       Arguments:
#           1    signal_spec
#   -----------------------------------------------------------------------

case $1 in
INT)    echo "$PROGNAME: Program aborted by user" >&2
	exit
	;;
TERM)   echo "$PROGNAME: Program terminated" >&2
	exit
	;;
*)      error_exit "$PROGNAME: Terminating on unknown signal"
	;;
esac
}


function root_check

{

#   -----------------------------------------------------------------------
#   Function to check if user is root
#   -----------------------------------------------------------------------

if [ "$(id | sed 's/uid=\([0-9]*\).*/\1/')" != "0" ]; then
error_exit "You must be the superuser to run this script."
fi
}


function ask_yn
{

#   ------------------------------------------------------------------------
#   Function to ask user YES/no - question
#           Arguments:
#                   1       question (required)
#   ------------------------------------------------------------------------
# Fatal error if required arguments are missing
if [ "$1" = "" ]; then
error_exit "ask_yn: missing argument 1"
fi

# Main function
local yn="_"
while [ "$yn" = "_" ]; do
echo -en "\n$1 [Y/n] "
read yn
case $yn in
    ""|y|Y) yn=0
	    ;;
    n|N)    yn=1
	    ;;
    *)      yn="_"
	    echo "Invalid response - please answer y or n"
	    ;;
esac
done
return $yn
}   # end of ask_yn


function prog_kill
{
#   ------------------------------------------------------------------------
#   Kills a program and waits until its really dead
#           Arguments:
#                   1       name of program to kill (required)
#   ------------------------------------------------------------------------
# Fatal error if required arguments are missing

if [ "$1" = "" ]; then
error_exit "prog_kill: missing argument 1"
fi

# Main function

if [ -n "$(pgrep $1)" ] ; then
pkill $1
while [ -n "$(pgrep $1)" ] ; do
    sleep 1
done
fi
}   # end of prog_kill


function add_bookmarks
{
#   ------------------------------------------------------------------------
#   Adds bookmarks to
#           Arguments:
#                   1       bookmarks-file (required)
#   ------------------------------------------------------------------------
# Fatal error if required arguments are missing

if [ "$1" = "" ]; then
error_exit "add_bookmarks: missing argument 1"
fi

# Main function
if ! grep -q "http://refugeesemancipation.com/" "$1" ; then
perl -pe 's@^(.*http://en-US.fxfeeds.mozilla.com/en-US/firefox/headlines.xml.*)$@\1\n        <DT><A HREF="http://refugeesemancipation.com/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH2AUNDi0JW1usDgAAAB10RVh0Q29tbWVudABDcmVhdGVkIHdpdGggVGhlIEdJTVDvZCVuAAAAaUlEQVQoz2Pkz97EQApgYWBguGs6AVlI+XQBhIEmDpFiwjQDUx26DcgGYzUVmcvEQCIgWQMLQRVwR0LcRg0brn4Vw+NpFjSrr34V87sWRYKndQS/b9JaRlo8aHN/HqBgxZmW8ANGUpM3ALM8I6KkiGNzAAAAAElFTkSuQmCC">Refugees Emancipation e.V. [Empowering Refugees Worldwide]</A>@;' -i "$1"
fi
if ! grep -q "https://we.riseup.net/refeman" "$1" ; then
perl -pe 's@^(.*http://refugeesemancipation.com/.*)$@\1\n        <DT><A HREF="https://we.riseup.net/refeman" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1gwUFRc6y1pE5AAAAS1JREFUOMud00Eo3nEcx/HXM0KtEGsHO6+VwkHKSUKJqxZtO1hKyVUpXBxcnMSJuUnPcnFz5GiH7TYpPQeT3Ge1RTxfB3/1T39/41O/y7fv+92nX78fGaliHNX+Iy+yhq9pH2EDFc8SnPK7k/f9rKCQsdKAz3ktZzuIEtHCfDKrKNDfx9cF/r1lLq/ZJGKf+Ea5leIcJ9+JIBY5Qk2e4BPiYwKkzw/K9Qw+BDZiGr8Q1cRZCr4kBtjOAtuwjr+I9JlPCbZvZ9334WEconwfRrwhLhLBFTHKT9RltWjCB3xBKS0pplqcE73soDLvEgv4cyd4x/UqVwdEmTgmmll+7JEdpVos4SW6WpmaYWuMY0zkCfYSuJTAWXmVJ9jENXqe/BeSnGENu56ZIdQ+tnQDUCN3ALH+HPEAAAAASUVORK5CYII=">refeman - riseup.net</A>@;' -i "$1"
fi
}   # end of add_bookmarks



#   -------------------------------------------------------------------
#   Program starts here
#   -------------------------------------------------------------------


##### Initialization And Setup #####

# Set file creation mask so that all files are created with 644 permissions.

umask 022


# Trap TERM, HUP, and INT signals and properly exit

trap "signal_exit TERM" TERM HUP
trap "signal_exit INT"  INT


##### Command Line Processing #####

if [ "$1" = "--help" ]; then
helptext
exit
fi

while getopts ":h" opt; do
case $opt in
h )     helptext
	exit ;;
* )     usage
	exit 1
esac
done

root_check


##### Main Logic #####

# Warning - continue?
if ! ask_yn "This script will (re)store configurations for all users & reboot your system!\n\nDo you want to continue?" ; then
exit
fi


# Add normal user
if ask_yn "Do you want to add a useraccount for normal users (none-administrators)?" ; then
echo -en "\nEnter username for new user: "
read user_name
until adduser --gecos "$user_name" "$user_name"; do
echo -en "\nEnter username for new user: "
read user_name
done
adduser $user_name fax
adduser $user_name cdrom
adduser $user_name tape
adduser $user_name audio
adduser $user_name video
adduser $user_name plugdev
adduser $user_name fuse
adduser $user_name netdev
adduser $user_name sambashare
if ask_yn "Do you want to enable login without password for the new account?" ; then
echo $user_name >> /etc/gdm/nopassusers
if ! grep -q '^auth    sufficient      pam_listfile.so item=user sense=allow file=/etc/gdm/nopassusers onerr=fail$' /etc/pam.d/gdm ; then
    sed -e 's#^@include common-auth$#auth    sufficient      pam_listfile.so item=user sense=allow file=/etc/gdm/nopassusers onerr=fail\n@include common-auth#g' -i /etc/pam.d/gdm
fi
fi
fi


# install automated security updates
if  [ ! -e "/etc/cron.weekly/apt-security-updates" ] &&\
[ ! -e "/etc/logrotate.d/apt-security-updates" ] &&\
ask_yn "Do you want to install automated security updates?" 
then
tar -xpjf "${PROGDIR}/apt-security-updates.tar.bz2" -C /etc/
fi

if [ -e /etc/apt/sources.list.d/medibuntu.list ] ; then
sudo apt-get update
else
sudo apt-get update
# Add medibuntu repository
echo -e "\nAdd medibuntu repository ..."
wget http://www.medibuntu.org/sources.list.d/$(lsb_release -cs).list --output-document=/etc/apt/sources.list.d/medibuntu.list ||\
error_exit "ERROR: Could not download http://www.medibuntu.org/sources.list.d/$(lsb_release -cs).list!"
sudo apt-get update && sudo apt-get --allow-unauthenticated install medibuntu-keyring && sudo apt-get update
fi

# install additional packages with prompts during istallation
echo -e "\ninstall packages with prompts during istallation ..."
aptitude -y install sun-java6-jre sun-java6-plugin || exit 1

# change from totem-gstreamer to totem-xine
prog_kill totem
aptitude -y install totem-xine totem-gstreamer-

# install additional multimedia packages
echo -e "\ninstall additional multimedia packages ..."
aptitude -y install flashplugin-nonfree gstreamer0.10-ffmpeg gstreamer0.10-pitfdll gstreamer0.10-plugins-bad gstreamer0.10-plugins-bad-multiverse gstreamer0.10-plugins-base gstreamer0.10-plugins-good gstreamer0.10-plugins-ugly gstreamer0.10-plugins-ugly-multiverse icedtea6-plugin libavcodec-unstripped-52 libdvdcss2 libdvdread4 libmp3lame0 libxine1-all-plugins ttf-mscorefonts-installer soundconverter sound-juicer streamripper totem-mozilla w32codecs mplayer vlc || exit 1

# install additional acessories, graphics, network & office packages
echo -e "\ninstall additional acessories, network & office packages ..."
aptitude -y install amsn filezilla gimp-help-en language-support-writing-en medit openoffice.org openoffice.org-help-en-us skype vim unrar || exit 1


# Update
echo -e "\nUpdate your system ..."
aptitude -y full-upgrade


# Add script flv-to-mp3
tar -xpjf "${PROGDIR}/flv-to-mp3.tar.bz2" -C /opt/


# Configure firefox
echo -e "\nConfigure firefox ..."
prog_kill firefox
add_bookmarks "/etc/firefox-3.0/profile/bookmarks.html"
tar -xpjf "${PROGDIR}/firefox-privacy-security.tar.bz2" -C /etc/cron.daily/
/etc/cron.daily/firefox-privacy-security
tar -xpjf "${PROGDIR}/searchplugins.tar.bz2" -C /usr/lib/firefox-addons/searchplugins/


# Set volumes
echo -e "\nSet volumes ..."
amixer set Master 90%
amixer set PCM 80%
amixer set Capture 80%


## Create variable for user-configuration
home_users=$(ls -1 /home)


# Install reset-script & execute for all users
echo -e "\nInstall reset-script & (re)store configurations for all users ..."
tar -xpjf "${PROGDIR}/restore-home.tar.bz2" -C /opt/
tar -xpjf "${PROGDIR}/restore-reset-buttons.tar.bz2" -C /etc/cron.daily/
for x in $home_users ; do
  cd /home/${x}/
  sudo -u $x tar --recursive-unlink --preserve -xjf /opt/restore-home/re-home.tar.bz2
  sudo -u $x sed -e "s#/home/re#/home/${x}#g" -i $(cat /opt/restore-home/grep-lr-home-re-filelist)
  sudo -u $x [ ! -e /home/${x}/Desktop ] && sudo -u $x mkdir /home/${x}/Desktop && sudo -u $x chmod 700 /home/${x}/Desktop
  tar -xpjf /opt/restore-home/reset-launcher.tar.bz2 -C /home/${x}/Desktop/
  cp -a /opt/flv-to-mp3 /home/${x}/
done

# Reboot
reboot

