#!/bin/sh

#/*****************************************************************************
# FUNCTION- mount_other
#
# Mount all non-CF and non-RAID drives that are found in the system.
# 
# NOTE: A proper primary drive must mount first (see PRIMARY_LIST).  If the
#       primary drive is not first in the /sys/block output, then drives prior
#       to it will not be mounted.
#/*****************************************************************************
function mount_other ()
{
  # The primary drive must mount as RW.  If it is RO, it will be unmounted and
  # the primary drive will be redirected to /tmp/hd0
  local HD=$(find /sys/block/ -mindepth 1 -maxdepth 1 -type d -name "loop*" -prune -o -name "md*" -prune -o -name "hde" -prune -o -printf "%f\n")
  for DRIVE in $HD; do
    local NOT_USE="FALSE"
    local PRIMARY=0
    local MOUNT_OK=0
    local READONLY=0

    # Flag drives that may be named hd* and part of raid
    for MATCH in $RAID_DEV; do
      if [[ $MATCH == $DRIVE* ]]; then # already in raid, do not use
        NOT_USE="TRUE"
      fi
    done

    # Check for a primary internal drive and flag it if found.  Note that only
    # the first mounted drive can be primary, so don't check for any others.
    if [ $CNT -eq 0 -a "$NOT_USE" == "FALSE" ]; then # first mount and used drive
      for MATCH in $PRIMARY_LIST; do
        if [ $MATCH == $DRIVE ]; then # set primary flag
          #echo "Setting primary flag for drive $DRIVE"
          PRIMARY=1
        fi
      done
    fi

    # Perform a mount for non-raid drives
    if  [ "$NOT_USE" == "FALSE" -a $CNT -gt 0 -o $PRIMARY -eq 1 ]; then
      # Make a directory for the mount point
      if [ ! -d "/media/hd${CNT}" ]; then mkdir /media/hd${CNT}; fi
      # Mount the drive, grossly assuming there is a single first partition, will
      # query for it later in proc partitions.
      logger -s -t "[MOUNTER]" "Mounting /dev/${DRIVE}1 on /media/hd${CNT}"
      mount /dev/${DRIVE}1  /media/hd${CNT} -o noatime,nodiratime,usrquota,commit=1,barrier=1,errors=continue
      # If mount was successful, set MOUNT_OK and set read-only state
      if [ $? -eq 0 ]; then # mount was successful
        MOUNT_OK=1
        READONLY=$(mount | grep "\/media\/hd0" | grep -c "ro,")
      fi
      # If a primary drive either failed to mount, or mounts read-only, disable it
      if [ $PRIMARY -eq 1 ]; then # primary drive
        if [ $MOUNT_OK -eq 1 ]; then # mounted OK
          if [ "$READONLY" == "1" ]; then # primary is read-only, umount it
            echo "Removing bad primary drive $CNT ($DRIVE)"
            logger -s -t "[MOUNTER]" -p user.warn "Primary drive ${DRIVE} resulted in read-only mount"
            umount /media/hd0
            if [ $? -eq 0 ]; then # umount was successful
              rmdir /media/hd0
              logger -s -t "[MOUNTER]" -p user.warn "Read-only primary drive ${DRIVE} has been removed"
            fi
          else           # primary mounted OK
            REDIRECT=0   # disable redirect
            if [ ! -e "/media/hd${CNT}/${QUOTA_UFILE}" ]; then
              quotacheck -u /media/hd${CNT}
            fi
            logger -s -t "[MOUNTER]" "Setting quota on /media/hd${CNT}" 
            setquota -u $QUOTA_ID $SOFT_LIMIT $HARD_LIMIT 0 0 -a /media/hd${CNT}
            quotacheck /media/hd${CNT}
            quotaon /media/hd${CNT}
            chown adtec:apache /media/hd${CNT}
            chmod 775 /media/hd${CNT} 
          fi
        else             # mount failure
          logger -s -t "[MOUNTER]" -p user.warn "Primary drive ${DRIVE} did not mount properly"
          echo "Ensuring that primary drive $DRIVE is not mounted"
          umount /media/hd0  # ensure umount
          if [ $? -eq 0 ]; then # umount was successful
            rmdir /media/hd0
            logger -s -t "[MIGRATE]" -p user.warn "Removed failed mount for primary drive ${DRIVE}"
          fi
        fi
        # always increment from primary, redirect will remount failed primary mounts
        let "CNT=CNT+1"
      else    # non-primary drive
        if [ $MOUNT_OK -eq 1 ]; then # non-primary drive mounted OK
          let "CNT=CNT+1"   # move to next drive
        else
          logger -s -t "[MOUNTER]" -p usr.warn "Failed to mount /dev/${DRIVE}1 on /media/hd${CNT}"
          umount /media/hd${CNT}  # ensure umount
        fi
      fi
    fi
  done
}

###############################################################################
#
# Configuration file for setting up the unit.
#
# Copyright (c) 2006
# License- GPL
# Author-  Andre G Ancelin
# Company- Adtec Digital, Inc.
# Date-    2006-06-02
# Last edit - 2006-11-30 Increased /tmp size to 64m to accomodate large releases
# This file normally just mounts all of the directories required to give the 
# product it's "personality".
#
# TODO:  detect existing partitions instead of assuming 1 exists for each drive
#
##############################################################################

for MOUNT in \
  "dev                 /dev                      none   bind,rw                     umount" \
  "etc                 /etc                      none   bind,rw                     umount" \
  "home                /home                     none   bind,rw                     umount" \
  "root                /root                     none   bind,rw                     umount" \
  "var                 /var                      none   bind,rw                     umount" \
  "media               /media                    none   bind,rw                     umount" \
  "tmpfs               /tmp                      tmpfs  size=48m                    umount" \
  "tmpfs               /var/tmp                  tmpfs  size=4m                     umount" \
  "tmpfs               /var/cache                tmpfs  size=256k                   umount" \
  "tmpfs               /var/lib                  tmpfs  size=256k                   umount" \
  "tmpfs               /var/lock                 tmpfs  size=256k                   umount" \
  "tmpfs               /var/run                  tmpfs  size=256k                   umount" \
  "usbfs               /proc/bus/usb             usbfs  noauto                      umount" \
  "sysfs               /sys                      sysfs  noauto                      umount" 
  
do
  do_mount "${MOUNT}"
done

# uncomment this to get get more kernel debug messages from printk 
#echo "4 4 1 7" > /proc/sys/kernel/printk


##############################################################################
# Drive management system
# The rest of script is basically an automounter system for the system drives
# We auto detect raid, CF only systems or hard drive systems and mount
# the drives as HD0, HD1, HD2.
##############################################################################
logger -s -t "[MOUNTER]" "Starting drive management system" 

# source in some stuff for this product
. etc/env.global

# list of all folders on the drive that adtec user needs to own
FOLDER_LIST="media dvc list osd shd schmi mvl rdy"
# folders only for DPI
DPI_FOLDER_LIST="schins verins"
# System folders
SYS_FOLDERS="log"
FREG_FOLDERS=".meta"

SOFT_LIMIT="100000"
HARD_LIMIT="120000"
QUOTA_ID="syslogd"
QUOTA_UFILE="aquota.user"

# test for hde8 and md0
declare HDE8=$(grep -c "hde8" /proc/partitions)
declare MD=$(lsraid -p | grep -o "md[0-4]")      
# The following was used once, but at time I noted md1,md2,md3 in /sys/block/folder.  Not
# sure how or why they showed up, but did not appear again.
#declare MD=$(find /sys/block/ -mindepth 1 -maxdepth 1 -type d -name "md*" -printf "%f\n")

# now get the devices belonging to the raid. 
if [ $MD ]; then  # must be a raid system, need devices
  RAID_DEV=$(grep "^device" /etc/raidtab | sed -e "s/device[ ]*\/dev\///")
  logger -s -t "[MOUNTER]" "Located $RAID_DEV" 
  raidstart /dev/md0
fi

#clear hdx from /media folder.  This allows only this script to add folders for mounting during boot.
find /media -mindepth 1 -maxdepth 1 -type d -name "hd*" -exec rm -rf {} \;
# clean up any residual smb mount points
find /media -mindepth 1 -maxdepth 1 -type d -name ".smb*" -exec rm -rf {} \;

# mount any persistent nfs/smb fstab residuals
if [ -e /etc/fstab ]; then
   mount -a
fi

declare -i CNT=0          # tracks drive mounts
declare -i REDIRECT=1     # Assume a redirect is necessary
# Create a list of allowed primary drives for the redirect test
declare PRIMARY_LIST="hda hdc sda sdb"

# The following can be re-ordered for priority HD0 -> HDn

# Mount raid drives, handles multiple drives
declare MD_COUNT=0
for DRV in $MD; do 
  if [ ! -d "/media/hd${CNT}" ]; then mkdir /media/hd${CNT}; fi
  mount /dev/md${MD_COUNT}  /media/hd${CNT} -o noatime,nodiratime,usrquota
  logger -s -t "[MOUNTER]" "Mounting /dev/md${MD_COUNT} on /media/hd${CNT}"
  chown adtec:apache /media/hd${CNT}
  chmod 755 /media/hd${CNT} 
  let "CNT=CNT+1"
  let "MD_COUNT=MD_COUNT+1"
  REDIRECT=0   # Primary drive is a raid system, do not redirect
done

# Mount remaining drives (non-CF and non-RAID)
mount_other

# test for cf only system
if [ $HDE8 -eq 1 ]; then 
  if [ ! -d "/media/hd${CNT}" ]; then mkdir /media/hd${CNT}; fi
  mount /dev/hde8 /media/hd${CNT} -o noatime,nodiratime,usrquota,commit=1
  if [ ! -e "/media/hd${CNT}/${QUOTA_UFILE}" ]; then
     quotacheck -u /media/hd${CNT}
  fi
  setquota -u $QUOTA_ID $SOFT_LIMIT $HARD_LIMIT 0 0 -a /media/hd${CNT}
  quotacheck /media/hd${CNT}
  quotaon /media/hd${CNT}
  logger -s -t "[MOUNTER]" "Mounting /dev/hde8 on /media/hd${CNT}"
  chown adtec:apache /media/hd${CNT}
  chmod 775 /media/hd${CNT} 
  let "CNT=CNT+1"
  REDIRECT=0   # Primary drive is a CF partition, do not redirect
fi


if [ $CNT -eq 0 ]; then
  logger -s -t "[MOUNTER]" "No drives have been mounted"
fi

# Redirect the primary drive /media/hd0 to /tmp/hd0 if the REDIRECT flag is set
if [ $REDIRECT -eq 1 ]; then
  mkdir /tmp/hd0
  if [ ! -d "/tmp/hd0" ]; then mkdir /tmp/hd0; fi
  if [ ! -d "/media/hd0" ]; then mkdir /media/hd0; fi
  chown adtec:apache /tmp/hd0
  chown adtec:apache /media/hd0
  mount --bind /tmp/hd0 /media/hd0
  logger -s -t "[MOUNTER]" -p user.warn "Redirected primary drive to tmp"
fi

HD0=/media/hd0

# setup folder permissions
for FOLD in $FOLDER_LIST; do
  if [ ! -d ${HD0}/${FOLD} ]; then
     mkdir ${HD0}/${FOLD}
  fi
  chown -R adtec:apache ${HD0}/${FOLD}
  chmod -R 775 ${HD0}/${FOLD}
  chmod g+s ${HD0}/${FOLD}
done

# setup system folders if needed
for FOLD in $SYS_FOLDERS; do
  if [ ! -d ${HD0}/${FOLD} ]; then
     mkdir ${HD0}/${FOLD}
  fi
  chown syslogd:root ${HD0}/${FOLD}
  chmod 755 ${HD0}/${FOLD}
done

# setup FREG folders if needed
for FOLD in $FREG_FOLDERS; do
  if [ ! -d ${HD0}/${FOLD} ]; then
     mkdir ${HD0}/${FOLD}
  fi
  chown fregd:apache ${HD0}/${FOLD}
  chmod 750 ${HD0}/${FOLD}
done

if [ "$PRODUCT" == "dpi" ]; then
  for FOLD in $DPI_FOLDER_LIST; do
  if [ ! -d ${HD0}/${FOLD} ]; then
     mkdir ${HD0}/${FOLD}
  fi
    chown adtec:users ${HD0}/${FOLD}
    chmod g+s ${HD0}/${FOLD}
  done
fi

# remove stale temp files (NEEDED?)
find ${HD0} -type f -name "\.tmp\.*" -exec rm {} \; &

# clean up any residual failed downloads
find /media -mindepth 1 -maxdepth 1 -type f -name ".pureftpd-upload*" -exec rm -rf {} \; &

# setup link so the chrooted ftp client can use absolute system path
if [ ! -e /media/media ]; then
 ln -s . /media/media
fi



logger -s -t "[MOUNTER]" "Drive mounts and linking complete"
