#!/bin/bash
if [ -z $CB_ENVDIR ]; then
    CB_ENVDIR=/opt/skyformai/etc
fi
AIPTOP=$(dirname $CB_ENVDIR)
if [ ! -f $CB_ENVDIR/proxy.yaml ] || [ ! -d $AIPTOP/work ]; then
    echo Please make sure AIP configuration directory $CB_ENVDIR
    echo and working directory $AIPTOP/work are set on the machine.
    echo "FAILED!!!"
    exit 1
fi

instp=$(dirname $0)
if [ ! -d $AIPTOP/work/proxy ]; then
    echo $AIPTOP/work/proxy does not exist. Please ensure the directory
    echo exists with the permission of 777.
    echo 'FAILED!!!'
    exit 1
fi
mkdir -p /var/log/aipproxy

if ! grep -q '\- name: proxy' $CB_ENVDIR/cb.yaml; then
    echo "Please configure the resource 'proxy' in cb.yaml under 'cluster:'. e.g."
    echo "cluster:"
    echo " resources:"
    echo ' - name: proxy'
    echo "   description: Number of ports configured in Proxy"
    echo "   type: number"
    echo "   direction: decrease"
    echo "   assign: yes"
    echo "   slotresource: no"
    echo '   instances: "1000@[all]"'
    echo "In above, 1000 means the total number of usable ports"
    echo "Make sure to restart the AIP service after the change"
    echo "FAILED!!!"
    exit 1
fi

systemctl stop aipproxy 2>/dev/null
cp $instp/aipproxy $instp/aipproxy_comm /usr/sbin
if [ ! -f /lib/systemd/system/aipproxy.service ]; then
    cat <<EOF > /lib/systemd/system/aipproxy.service
[Unit]
Description=AIP Proxy
After=network.target remote-fs.target

[Service]
Environment=CB_ENVDIR=$CB_ENVDIR
ExecStart=/usr/sbin/aipproxy
Restart=always
RestartSec=15

[Install]
WantedBy=multi-user.target
EOF
fi

systemctl enable aipproxy
systemctl restart aipproxy

echo Installation completed
