#!/usr/bin/env bash
#
# Copyright (c) 2011 VMware, Inc.  All rights reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# 

#
# VAMI first boot operations.

export PATH=$PATH:/opt/vmware/bin

function echoerr { echo "ERROR: $@" 1>&2; }

if [ -x /opt/vmware/share/sfcb/genSslCert.sh -a -d /opt/vmware/etc/sfcb ]; then
    /opt/vmware/share/sfcb/genSslCert.sh /opt/vmware/etc/sfcb
fi
if [ -x /opt/vmware/share/lighttpd/genSslCert.sh -a -d /opt/vmware/etc/lighttpd ]; then
    /opt/vmware/share/lighttpd/genSslCert.sh /opt/vmware/etc/lighttpd
fi

if [ -x /opt/vmware/share/vami/vami_ovf_process ]; then
    /opt/vmware/share/vami/vami_ovf_process --settimezone
fi

# regen /etc/ntp.keys
if [ -f /etc/ntp.keys ]; then
    rpmScript="./rpmScript";
    genKeyScript="./genNtpKey.sh";
    rpm -q --scripts ntp > $rpmScript
    startLine=`grep -n "postinstall scriptlet" $rpmScript |awk -F: '{print \$1}'`
    startLine=`expr $startLine + 1`
    lines=`grep -n 'scriptlet' $rpmScript | awk -F: '{print $1}'`
    endLine=`for n in $lines; do if [[ $n -gt $startLine ]]; then echo $n; break; fi; done`
    endLine=`expr $endLine - 1`
    sed -n "$startLine,${endLine}p" $rpmScript > $genKeyScript
    chmod 755 $genKeyScript

    mv /etc/ntp.keys  /etc/ntp.keys.bak
    /bin/sh $genKeyScript 1
    rm $rpmScript
    rm $genKeyScript
    if [ ! -f /etc/ntp.keys ]; then
        mv /etc/ntp.keys.bak /etc/ntp.keys
        touch /tmp/failRegenNtpKey
    else
        rm /etc/ntp.keys.bak
    fi
    if [ -d /etc/systemd ]; then
        systemctl restart ntpd
    else
        service ntp restart
    fi
    echo "regen ntp.keys, done"
fi

if [ -x /opt/vmware/share/vami/subsequentboot ]; then
    /opt/vmware/share/vami/subsequentboot
fi
