#!/bin/bash
#Create empty directories
IO_USER=$USER
NODE=`which node`
#Create user if first install
#if [ ! -f "/opt/yunkong2/conf/yunkong2.json" ]; then
#    if [ $(cat /etc/passwd | grep "/home" |cut -d: -f1 | grep '^yunkong2$' | wc -l) -eq 0 ]
#    then
#        read -p "Use current user '$USER' for yunkong2? If not, the 'yunkong2' user will be created.! [Y/n]" yn
#        case $yn in
#            [Nn]* ) echo "Create user yunkong2 ...";
#                    apt-get install sudo;
#                    useradd yunkong2;
#                    adduser yunkong2 sudo;
#                    IO_USER=yunkong2;
#                    break;;
#            [Yy]* ) echo "Use user '$USER' for yunkong2.";;
#            * ) echo "Use user $USER for yunkong2.";;
#        esac
#    else
#        IO_USER=yunkong2
#    fi
#else
    if [ $(cat /etc/passwd | grep "/home" |cut -d: -f1 | grep '^yunkong2$' | wc -l) -eq 0 ]
    then
        IO_USER=$USER
    else
        IO_USER=yunkong2
    fi
    echo "Use user $IO_USER for install."
#fi

## if yunkong2.sh not exists. Copy it
if [ ! -f "/etc/init.d/yunkong2.sh" ]; then
    cp @@PATH@@../yunkong2/install/linux/yunkong2.sh /etc/init.d/yunkong2.sh
fi
if [ ! -f "/usr/bin/yunkong2" ]; then
    echo 'node @@PATH@@yunkong2.js $1 $2 $3 $4 $5' > /usr/bin/yunkong2
fi
if [ ! -f "/usr/bin/iob" ]; then
    echo 'node @@PATH@@yunkong2.js $1 $2 $3 $4 $5' > /usr/bin/iob
fi

#Set rights
echo "Set permissions..."
#find @@PATH@@ -type d -exec chmod 777 {} \;
#find @@PATH@@ -type f -exec chmod 777 {} \;
#chown -R $IO_USER:$IO_USER @@PATH@@
chmod 755 /etc/init.d/yunkong2.sh
chmod 755 /usr/bin/yunkong2
chmod 755 /usr/bin/iob

#Replace user pi with current user
sed -i -e "s/yunkong2USER=.*/yunkong2USER=$IO_USER/" /etc/init.d/yunkong2.sh
NODE=${NODE//\//\\/}
sed -i -e s/NODECMD=.*/NODECMD=$NODE/ /etc/init.d/yunkong2.sh
chown root:root /etc/init.d/yunkong2.sh
update-rc.d yunkong2.sh defaults

# Start the service!
echo "Start yunkong2..."
cd @@PATH@@
#chmod -R 777 *
./yunkong2 start
echo "call http://ip_address:8081/ in browser to get the AdminUI of yunkong2"
