#!/bin/bash
# Setup provo servers /home
###
# chkconfig: 235 50 50
# description: setup /home
###

sym_home() {
  # Mount bind /ramdisk/home over /home if no one is there
  if ! [ -d "/home" ]
  then
    mkdir -m 751 /home
    chown root:wheel /home
  fi
  if !( grep -q ":/home/" /etc/passwd ) && !(grep -qoP "/dev/sd\w+ /home " /proc/mounts)
  then
    if ( grep -q "tmpfs /ramdisk" /proc/mounts )
    then
      chmod 0711 /ramdisk
      if [ ! -d "/ramdisk/home" ]; then
        mkdir /ramdisk/home
        chmod 0711 /ramdisk/home
      fi

      if ( grep -q "tmpfs /home" /proc/mounts )
      then
        umount -l /home
      fi
      for user in $( ls -A /var/cpanel/users ); do
        if [ $user != "root" ]
        then
          rm -f /ramdisk/home/$user
          grep -P "^$user:" /etc/passwd | cut -d':' -f6 | xargs -i ln -s {} /ramdisk/home/$user
	  chown -h ${user}. /ramdisk/home/$user
        fi
      done
      chown root:wheel /home
      chmod 0751 /home
      mount --bind -o ro,noatime,nodiratime,nosuid,nodev /ramdisk/home /home
      if [[ `uname -r | grep -oP "\d+\.\d+\.\d+"` > "2.6.25" ]]
      then
        mount -o remount,ro /ramdisk/home
      fi
    fi
  fi

  # Create cpanel files and symlinks so that stuff still works
  CPANEL_FILES=(".cpan" ".cpanm" ".cpcpan" "cpeasyapache" "cprestore" "MIRRORING.FROM" "hgbackupdir")
  for file in ${CPANEL_FILES[@]}
  do
    if ! [ -d "/admin/$file" ]
    then
      mkdir /admin/$file
    fi
    if ! [ -L "/ramdisk/home/$file" ]
    then
      rm -rf /ramdisk/home/$file
      ln -sf /admin/$file /ramdisk/home/$file
    fi
    if [ ! -L /ramdisk/home/APACHE_ARCHIVES ]; then
      ln -s /home1/APACHE_ARCHIVES /ramdisk/home/APACHE_ARCHIVES
      if [ $? == 0 ]; then
        /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null
      fi
    fi
  done

  HOME1_DIRS=("APACHE_ARCHIVES" "virtfs" "hgtransfer" "transfer_backups" "apachelogs")
  for file in ${HOME1_DIRS[@]}
  do
      if ! [ -d "/home1/${file}" ]; then
        mkdir -p /home1/$file
      fi
      ln -sf /home1/$file /ramdisk/home/
  done
}

case "$1" in
  start)
    sym_home;
    exit 0;
    ;;
  *)
    echo "usage: $0 {start}"
    ;;
esac
