#!/bin/bash


IPV6CHECK=ipv6.google.com
IPV4CHECK=google.com
IPV6WAITTIME=5
SLAPOS_CONFIGURATION=/etc/opt/slapos/
${ONLY_SLAPFORMAT:=false}


if [ $ONLY_SLAPFORMAT = false ]; then
    if [ ! -f  $SLAPOS_CONFIGURATION/slapos.cfg ]; then
        echo "No slapos.cfg found"
        exit 1
    fi

    echo "Starting slap script"

    # Check ipv4
    echo "Checking IPv4 connectivity..."
    ping -c 2 $IPV4CHECK >/dev/null 2>&1
    while [ $? != 0 ]; do
        echo "IPv4 is not ready yet."
        sleep 2
        ping -c 2 $IPV4CHECK >/dev/null 2>&1
    done

    # Launch openvpn
    if [ -f $SLAPOS_CONFIGURATION/openvpn-needed ]; then
        echo "Starting openvpn..."
        /etc/init.d/openvpn start
    fi

    # Wait for ipv6 connection to be ready
    echo "Checking IPv6 connectivity. This may take a few seconds..."
    ping6 -c 2 $IPV6CHECK >/dev/null 2>&1
    while [ $? != 0 ];
    do
        echo "IPv6 is not ready yet."
        sleep 2
        ping6 -c 2 $IPV6CHECK >/dev/null 2>&1
    done
else
    sleep 15
fi

# Run slapformat
i=1
echo -n "Running slapos node format..."
SLAPOS_FORMAT_COMMAND="/opt/slapos/bin/slapos node format --cfg $SLAPOS_CONFIGURATION/slapos.cfg --now --log-file=/opt/slapos/log/slapos-node-format.log"
$SLAPOS_FORMAT_COMMAND
while [ $? != 0 ]; do
    sleep $(($i*60))
    if [ $i -le 20 ]; then
        let i++
    fi
    echo "Retrying slapos node format"
    $SLAPOS_FORMAT_COMMAND
done

if [ $ONLY_SLAPFORMAT = false ]; then
    # Run bang
    i=1
    echo -n "Banging..."
    /opt/slapos/bin/bang -m "Rebooted" $SLAPOS_CONFIGURATION/slapos.cfg
    while [ $? != 0 ]; do
        sleep $(($i*60))
        if [ $i -le 20 ]; then
            let i++
        fi
        echo "Retrying Bang"
        /opt/slapos/bin/bang -m "Rebooted" $SLAPOS_CONFIGURATION/slapos.cfg
    done
    echo "done."

    # Delete timestamp of all partitions so that it will force slapgrid to process them.
    rm /srv/slapgrid/slappart*/.timestamp 2>/dev/null
fi

exit 0