#!/bin/bash

#   -------------------------------------------------------------------
#
#   Shell program to set up Xubuntu 9.10 (i386) for use in internetcafes.
#
#   Copyright 2010, 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/reset-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) 
#   2009-11-05  9.10.0  script-version-nrs start with Xubuntu-version-nr. now,
#                       use functions, 
#                       use xubuntu-restricted-extras instead of single pkgs 
#                       use mozilla-mplayer instead of totem-mozilla
#                       exchanged login without pw with auto-login
#                       not changing to totem-xine anymore
#   2010-01-18  9.10.1  added realplayer, xine-ui, totem-mozilla
#                       removed mozilla-mplayer, libmp3lame0 
#                       workaround for ttf-mscorefonts-installer
#                       install sound-juicer without recommended pkgs
#   -------------------------------------------------------------------


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

STARTWD=$(pwd)
PROGNAME=$(basename $0)
PROGDIR=$(dirname $0)
VERSION="9.10.1"



#   -------------------------------------------------------------------
#   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.10 (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
echo "${PROGNAME}: ${1:-"Unknown Error"}" >&2
exit 1
}


function signal_exit
{
# Function to handle termination signals
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

# 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
 
# 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 start_warning {
# Warning - continue?
if ! ask_yn "This script will (re)store configurations for all users & reboot your system!\nDo you want to continue?" ; then
  exit
fi
}

function add_user {
# 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 adm
  adduser $user_name dialout
  adduser $user_name fax
  adduser $user_name cdrom
  adduser $user_name tape
  adduser $user_name audio
  adduser $user_name dip
  adduser $user_name video
  adduser $user_name plugdev
  adduser $user_name fuse

  if ask_yn "Automatically login as $user_name?" ; then
    echo -e "\n[daemon]\nTimedLoginEnable=false\nAutomaticLoginEnable=true\nTimedLogin=$user_name\nAutomaticLogin=$user_name\nTimedLoginDelay=30" > /etc/gdm/custom.conf
  fi
fi
}

function automated_security_updates
{
# 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
}

function add_medibuntu {
# Add medibuntu repository
if [ -e /etc/apt/sources.list.d/medibuntu.list ] ; then
  echo -e "\nUpdate package informations ...\n"
  sudo apt-get update
else
  sudo apt-get update
  echo -e "\nAdd medibuntu repository ...\n"
  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
}

function update_old {
# Update from older scriptversion
if [ -e /opt/flv-to-mp3 ] ; then
  echo -e "\nUpdate from old scriptversion ...\n"
  rm /opt/flv-to-mp3
  rm -r /opt/reset-home/
  rm /home/*/Desktop/flv-to-mp3
  aptitude -y purge gnome-media gnome-media-common gstreamer0.10-pulseaudio libgnome-media0 libpulse-browse0 libpulse-mainloop-glib0 libspeexdsp1 pulseaudio pulseaudio-esound-compat pulseaudio-module-udev pulseaudio-module-x11 pulseaudio-utils sound-juicer mozilla-mplayer
fi
}

function pkgs_with_prompts {
  # install packages with prompts during istallation
  echo -e "\nInstall packages with prompts during istallation ...\n"
  aptitude -y install sun-java6-jre || exit 1
}

function pkgs_multimedia {
# install additional multimedia packages
echo -e "\nInstall additional multimedia packages ...\n"
aptitude -y install xubuntu-restricted-extras sun-java6-plugin libdvdcss2 libdvdnav4 libdvdread4 libxine1-all-plugins ffmpeg mplayer realplayer soundconverter streamripper totem-mozilla vlc xine-ui || exit 1
aptitude -R -y install sound-juicer || exit 1
# libavcodec-unstripped-52 libmp3lame0 
sudo /usr/share/doc/libdvdread4/install-css.sh
}


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

function pkgs_upgrade {
# Upgrade
echo -e "\nUpdate your system ...\n"
aptitude -y full-upgrade
}

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://fxfeeds.mozilla.com/en-US/firefox/livebookmarks/.*)$@\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

function configure_firefox {
# Configure firefox
echo -e "\nConfigure firefox ...\n"
prog_kill firefox
add_bookmarks "/etc/firefox-3.5/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/
}


function install_reset_home {
# Install reset-script
echo -e "\nInstall reset-script ...\n"
tar -xpjf "${PROGDIR}/reset-home.tar.bz2" -C /opt/
tar -xpjf "${PROGDIR}/restore-reset-buttons.tar.bz2" -C /etc/cron.daily/
/etc/cron.daily/restore-reset-buttons
}

function reset_home {
# Reset configurations in homefolders of all uses
echo -e "\nReset configurations in homefolders of all uses ...\n"
for x in $home_users ; do
  cd /home/${x}/
  sudo -u $x tar --recursive-unlink -xpjf /opt/reset-home/reset-home.tar.bz2
  sudo -u $x sed -e "s#homeresetuser#${x}#g" -i $(cat /opt/reset-home/filelist-replace-username)
done
cd "$STARTWD"
}

function audio_extras {
# Add alsamixer-launcher
echo -e "\nAdd audio-extras ...\n"
tar -xpjf "${PROGDIR}/audio-extras.tar.bz2" -C /opt/
/opt/audio-extras/amixer-reset
for x in $home_users ; do 
  sudo -u $x tar -xpjf /opt/audio-extras/xterm-alsamixer-launcher.tar.bz2 -C /home/$x/Desktop/
  sudo -u $x ln -s /opt/audio-extras/extract-audio /home/$x/Desktop/
done
}


#   -------------------------------------------------------------------
#   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 #####

start_warning
add_user
automated_security_updates
add_medibuntu
update_old
pkgs_with_prompts
pkgs_multimedia
pkgs_add
pkgs_upgrade
configure_firefox
## Create variable for user-configurations
home_users=$(ls -1 /home)
install_reset_home
reset_home
audio_extras
reboot

