#!/bin/sh

EMS_IP="$1"
template_sync() {
    cd /root
    if [ $? -ne 0 ] ; then
        echo "Error, cannot change to directory"
        exit 1
    fi

    rm -rf copy_dir/*
    mkdir -p copy_dir
    cd copy_dir
    if [ $? -ne 0 ] ; then
        echo "Error, cannot change to copy_dir"
        exit 2
    fi

    sshpass -p lnxall123 scp -r -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null \
        "root@${EMS_IP}:/app/template" ./
    if [ $? -ne 0 ] ; then
        echo "Error, failed to scp template files."
        rm -rf /root/copy_dir
        exit 3
    fi

    if [ ! -d template ] ; then
        echo "Error, template directory not found."
        rm -rf /root/copy_dir
        exit 4
    fi

    rm -rf /app/template
    mv -v -f template /app/
    return 0
}

if [ -z "${EMS_IP}" ] ; then
    echo "Error, EMS IP address not specified."
    exit 2
fi
template_sync
exit 0
