#!/bin/sh
# Author: Blake, Kuo-Lien Huang
# License: GPL
# Desctription: chanage KDE theme

DIA="/usr/bin/dialog"
TMP=$(mktemp /tmp/theme.XXXXXX)

if [ ! -L $HOME/.kde ]; then
  echo "I found your KDE Style/Theme is a new one."
  echo -n "Do you want to save it [Y/n]? "
  read ANS
  if [ "$ANS" = "" -o "$ANS" = "Y" -o "$ANS" = "y" ]; then
    $DIA \
      --backtitle "NCHC - National Center for High-Performace Computing" \
      --title "NCHC OpenSource TaskFoce Solution" \
      --inputbox "Please input the name for this new Style/Theme" 12 80 "mystyle" 2> $TMP
    NEWONE=$(cat $TMP)
    NEWONE=${NEWONE/ /-}
    mv $HOME/.kde $HOME/.drbl/.$NEWONE
    ln -fs .drbl/.$MODE $HOME/.kde
  else
    echo "Warning!! Your new KDE Style/Theme will be deleted !!!"
    echo -n "Are you sure [N|y]? "
    read ANS
    if [ "$ANS" = "" -o "$ANS" = "N" -o "$ANS" = "n" ]; then 
      echo "Abort!"
      exit 
    fi
  fi
fi

n_themes=0
themes=""
for theme in `ls -al --time-style=long-iso $HOME/.drbl/ | awk '{ print $8; }'`; do
  if [ "$theme" != "." -a "$theme" != ".." -a "$theme" != "" ]; then
    theme=${theme#.*}
    desc=${theme/-/_}
    themes="$themes $theme $desc off"
    n_themes=`expr $n_themes + 1`
  fi
done

$DIA \
--backtitle "NCHC - National Center for High-Performace Computing" \
--title "NCHC OpenSource TaskFoce Solution" \
--radiolist "Switch the KDE style/theme for user:" 24 80 $n_themes $themes 2> $TMP
MODE=$(cat $TMP)
rm -f $TMP

if [ -z "$MODE" ]; then
  echo "You didn't choose any theme to chanage! Abort!!"
  exit
fi

# change mode
if [ -e $HOME/.drbl/.$MODE ]; then
  rm -rf $HOME/.kde
  ln -fs .drbl/.$MODE $HOME/.kde
else
  echo "$HOME/.drbl/.$MODE doesn't exist! Abort!"
  exit
fi

# root
if [ "$UID" = "0" ]; then
  echo -n "Do you want to change all the other users' mode to $MODE [y/N]?"
  read ANS
  if [ "$ANS" = "Y" -o "$ANS" = "y" ]; then
    TMP=`mktemp /tmp/theme.XXXXXX`
    ls -l --time-style=long-iso /home > $TMP
    while read x x usr grp x x x dir; do
      if [ "$dir" = "" -o "$dir" = "partimag" ]; then continue; fi
      # if $MODE doesn't exist
      if [ ! -e /home/$dir/.drbl/.$MODE ]; then
        mkdir -p /home/$dir/.drbl
        cp -a $HOME/.drbl/.$MODE /home/$dir/.drbl/
        chown -R $usr.$grp /home/$dir/.drbl
      fi
      # link to it
      rm -rf /home/$dir/.kde
      ln -fs .drbl/.$MODE /home/$dir/.kde
    done < $TMP
    rm -f $TMP
  fi
fi
