11 November 2010

Enable/Disable Apache virtual hosts on Ubuntu with Zenity

Here is a simple bash script I use to toggle virtual hosts in a GUI window.

#!/bin/bash
# get available & enables site names & set corresp-ly checkboxes in the following zenity list
vh_avail=(`ls -B /etc/apache2/sites-available/`);

i=0
s=""

while (( i< ${#vh_avail[*]} ))
do
 if [ -f /etc/apache2/sites-enabled/${vh_avail[$i]} ] ; then 
  s=$s"TRUE "
 else 
  s=$s"FALSE "
 fi
 s=$s${vh_avail[$i]}" "
 
 (( ++i ))
done

# get vhost name

vhosts=`(zenity --list --width=700 --height=500 --title="Choose vhost" \
 --checklist --column="" --column="vhost" $s)`;

case $? in 
 0) # OK
   a=(`echo "$vhosts"|tr "\|" " "`);
   i=0;
   di=0;
   
   #disable all
   
   while (( i< ${#vh_avail[*]} ))
   do
    if [ -f /etc/apache2/sites-enabled/${vh_avail[$i]} ] ; then 
     a2dissite ${vh_avail[$i]}
    fi
    (( ++i ))
   done
   
   # enable needed
   i=0;   
   while ((i < ${#a[*]}))
   do 
    if [ -f /etc/apache2/sites-available/${a[$i]} ] ; then
     a2ensite ${a[i++]}
    else
     (( di++ ))
    fi
   done 
   
   info="${#a[*]} vhosts enabled";
   
   if (( di>0 ));then
    info="$info\n$di vhosts not found in /etc/apache2/sites-available/"
    zenity --warning --text="$info"
   else 
    zenity --info --text="$info"
   fi
   
   # reload apache
   /etc/init.d/apache2 restart #reload not always works
  ;;
 1) # Cancel
  exit 0
  ;; 
esac
So you can make a desktop launcher with command
gksudo /share/scripts/bash/vhosts_ed.sh