
# SHARD-QUERY AWS RAID AUTO-CONFIGURATION

if [ -d "/media/ephemeral0/lost+found" ]; then
  echo Unmounting sdb
  umount /dev/sdb
fi

if [ -e /tmp/mdadm.log ]; then
  mv /tmp/mdadm.log /tmp/mdadm.log.$(date +%s)
fi

echo "Starting MD device assembly" > /tmp/mdadm.log
if [ -f /dev/md127 ]; then
  mdadm --stop /dev/md127
fi

if [ -f /dev/md0 ]; then
  echo "/dev/md0 is already configured"
  echo "/dev/md0 is already configured" >> /tmp/mdadm.log
else 
  if [ -e "/dev/sde" ]; then
    mdadm -q --assemble /dev/md0 /dev/sdb /dev/sdc /dev/sdd /dev/sde >> /tmp/mdadm.log
  else
    mdadm -q --assemble /dev/md0 /dev/sdb /dev/sdc >> /tmp/mdadm.log
  fi
  
  if [ -e "/dev/md0" ]; then
    echo "RAID assembled!"
    echo "RAID assembled!" >> /tmp/mdadm.log
  else
  
    echo "Creating RAID0 (stripe) device"
    echo "Creating RAID0 (stripe) device" >> /tmp/mdadm.log
    
    if [ -e "/dev/sde" ]; then
      echo "FOUR ephemeral devices detected"
      echo "FOUR ephemeral devices detected" >> /tmp/mdadm.log
      dd if=/dev/zero of=/dev/sdb bs=1k count=1024 >> /tmp/mdadm.log
      dd if=/dev/zero of=/dev/sdc bs=1k count=1024 >> /tmp/mdadm.log
      dd if=/dev/zero of=/dev/sdd bs=1k count=1024 >> /tmp/mdadm.log
      dd if=/dev/zero of=/dev/sde bs=1k count=1024 >> /tmp/mdadm.log
      mdadm --create /dev/md0 -n 4 -l 0 /dev/sdb /dev/sdc /dev/sdd /dev/sde >> /tmp/mdadm.log
    else
      echo "TWO ephemeral devices detected" 
      echo "TWO ephemeral devices detected" >> /tmp/mdadm.log
      dd if=/dev/zero of=/dev/sdb bs=1k count=1024 >> /tmp/mdadm.log
      dd if=/dev/zero of=/dev/sdc bs=1k count=1024 >> /tmp/mdadm.log
      mdadm --create /dev/md0 -n 2 -l 0 /dev/sdb /dev/sdc >> /tmp/mdadm.log
    fi
  
    echo "Creating ext4 filesystem" 
    echo "Creating ext4 filesystem" >> /tmp/mdadm.log
    mkfs.ext4 /dev/md0 >> /tmp/mdadm.log
  
  fi
fi

echo Mounting file system
mount /dev/md0 /media > /tmp/mount.log

echo "Relocating MySQL files if necessary"
if [ -d /media/infobright ]; then
  echo "Infobright moved already"
else
  if [ -f /usr/local/infobright ]; then
    rm /usr/local/infobright
    mv /usr/local/info* /media/infobright
    chown -R mysql:mysql /media/infobright
    ln -s /media/infobright /usr/local
    ln -s /media/infobright /usr/local/infobright-4.5.0-x86_x64
    chown mysql:mysql /usr/local/info*
  else
    mkdir /media/infobright
  fi
fi


if [ -d /media/mysql ]; then
  echo "MySQL moved already"
else
  if [ -d /var/lib/mysql  ]; then
    mv /var/lib/mysql /media
    chown -R mysql:mysql /media/mysql
    ln -s /media/mysql /var/lib
    chown mysql:mysql /var/lib/mysql
  else
    mkdir /media/mysql
  fi
fi

service mysqld-ib start
service mysqld start

touch /var/lock/subsys/local.mdadm
