# FreePBX Distro Kickstart
#
# Copyright (c) 2016 Sangoma Technologies Corporation - All Rights Reserved.
#
# This is NOT Open Source software.
#
# You are NOT permitted to modify, reverse engineer, or redistribute this
# file without explicit permission from Sangoma Technologies Corporation.
#
# Permission is only granted to use this file on an unmodified distribution
# of FreePBX Distro. Any other use is strictly prohibited.
#
# THIS SOFTWARE IS PROVIDED 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
# SANGOMA TECHNOLOGIES CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;  LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
%pre --log /root/diskpart.log --interpreter /bin/bash
set -x -v
exec 1>/tmp/ks-pre.log 2>&1

# Function for joining arrays together
function join { local IFS="$1"; shift; echo "$*"; }

# Function to get explicit by-id of device
function getid {
	# Make sure we change ! to / for /dev/cciss/c0d0 etc.
	DEV=$(echo $1 | sed 's^!^/^')
	DEVID=$(/usr/sbin/udevadm info --query=property --name=/dev/$DEV | grep DEVLINKS= | cut -d= -f2 | cut -d\  -f1)
	# If we didn't get a device id, then just return the path. This can happen
	# with virtual devices.
	if [ ! "$DEVID" ]; then
		echo $DEV
	else
		echo $DEVID
	fi
}

# Is this machine booted in EFI mode? Assume no.
UEFI=false

[[ -e /sys/firmware/efi ]] && UEFI=true

COUNT=0

# Are we skipping HDD configuration?
if [[ "$(grep skip-hdd-setup /proc/cmdline)" ]]; then
	echo "# Skipping HDD Setup" > /tmp/partitioning
	exit
fi

# Get a list of our disks on this machine
lsblk -bdrno KNAME,TYPE,SIZE,RM,HCTL > /tmp/lsblk.out

# Loop throught them
while read DEV TYPE SIZE RM HCTL; do
    # If it's not a disk, ignore
    if [[ $TYPE != "disk" ]]; then
        continue;
    fi

    # If it's a ram disk, ignore
    if [[ $DEV == zram* ]]; then
	continue;
    fi

    # Automatically ignore any removable devices
    #
    # TODO: This may need more work.  (Check for 8gb or less?)
    #
    if [[ $RM == 1 ]]; then
	continue;
    fi

    COUNT=$(( $COUNT + 1 ))
    DEVICE[${COUNT}]=$(getid $DEV)
    STDDEVICE[${COUNT}]=$DEV
    SIZE[${COUNT}]="$SIZE"
    TYPE[${COUNT}]="$TYPE"

    # Make sure there's not any biosraid cruft on the device, which causes anaconda to crash
    dd if=/dev/zero of=$DEV bs=512 seek=$(( $(blockdev --getsz /dev/$DEV) - 1024 )) count=1024
done < /tmp/lsblk.out

echo "creating partitioning config"
VALIDDRIVES=$(join , ${DEVICE[*]})


# Are we not doing LVM?
if [[ "$(grep nolvm /proc/cmdline)" ]]; then
	# Nuke the disk's current partition information
	D=/dev/${STDDEVICE[1]}
	dd if=/dev/zero of=$D bs=1M count=1
	parted -s $D mklabel msdos
	# Create root, swap, and make it active.
	if [[ "$(grep tiny-10g /proc/cmdline)" ]]; then
		parted -a optimal -s $D mkpart primary ext3 0% 9G
		parted -a optimal -s $D mkpart primary linux-swap 9G 10G
	else
		parted -a optimal -s $D mkpart primary ext3 0% 95%
		parted -a optimal -s $D mkpart primary linux-swap 95% 100%
	fi
	parted -s $D set 1 boot on
	partprobe $D

cat << EOF > /tmp/partitioning
zerombr
bootloader --boot-drive=${DEVICE[1]} --driveorder=$(join , ${STDDEVICE[*]}) --append="net.ifnames=0 biosdevname=0"
part / --label=root --fstype ext3 --onpart=${D}1
part swap --onpart=${D}2
EOF

	exit
fi

# Otherwize
cat << EOF > /tmp/partitioning
zerombr
clearpart --initlabel --all --drives=${VALIDDRIVES}
bootloader --boot-drive=${DEVICE[1]} --driveorder=$(join , ${STDDEVICE[*]}) --append="net.ifnames=0 biosdevname=0"
reqpart

EOF

# If this is a tiny-10g install, then just allocate 10gb to /, as it
# can be expanded later if needed. Otherwise, minimum of 4gb, and
# grow as much as possible
if grep tiny-10g /proc/cmdline; then
	VOL="--size=10000"
else
	# We leave some slack space for snapshots or volumes
	# to be created later
	VOL="--percent=95"
fi



# Do we have a single device? 
if [[ $COUNT == 1 ]]; then
    echo "part /boot --label=bootvol --fstype ext4 --size=2000"  >> /tmp/partitioning
    echo "part pv.20 --label=rootvg --grow --size=4000"  >> /tmp/partitioning
elif [[ $COUNT == 2 ]]; then
# Do we have 2 identically sized drives? If so, RAID1 them.
    # Are they the same size?
    if [[ "${SIZE[1]}" == "${SIZE[2]}" ]]; then
        # Mirror these disk!
        # /boot volume is always 5gb
        BOOTDEVICES=""
        LVMDEVICES=""
        PART=0
        for d in "${DEVICE[@]}"; do
            echo "part raid.0${PART} --size=2000 --ondisk=$d" >> /tmp/partitioning
            echo "part raid.1${PART} --grow --size=4000 --ondisk=$d" >> /tmp/partitioning
            BOOTDEVICES="${BOOTDEVICES} raid.0${PART}"
            LVMDEVICES="${LVMDEVICES} raid.1${PART}"
            PART=$(( $PART + 1 ))
        done
        echo "raid /boot --level=1 --device=md0 --fstype ext4 --label=bootvol ${BOOTDEVICES}" >> /tmp/partitioning
        echo "raid pv.20 --level=1 --device=md1 --label=rootvg ${LVMDEVICES}" >> /tmp/partitioning
    else
        # Different sizes. Just use the first.
        echo "part /boot --label=bootvol --fstype ext4 --size=2000"  >> /tmp/partitioning
        echo "part pv.20 --label=rootvg --grow --size=4000"  >> /tmp/partitioning
    fi
else
    # TODO: RAID5, HA setup etc.
    # We don't know what to do. So just leave HDD setup to the end user.
    exit
fi

cat << EOF >> /tmp/partitioning
volgroup SangomaVG  pv.20

logvol swap --fstype swap --name=swaplv1 --vgname=SangomaVG --recommended
logvol / --fstype xfs --name=root --vgname=SangomaVG $VOL
EOF

%end
