#!/bin/sh
IO_USER=yunkong2
NODE=`which node`

## if yunkong2.sh not exists. Copy it
if [ ! -f "/usr/local/etc/rc.d/yunkong2" ]; then
    cp @@PATH@@../yunkong2/install/freebsd/yunkong2 /usr/local/etc/rc.d/yunkong2
fi
if [ ! -f "/usr/local/bin/yunkong2" ]; then
    echo '${NODE} @@PATH@@yunkong2.js $1 $2 $3 $4 $5' > /usr/local/bin/yunkong2
fi

# Create user
pw groupadd -n yunkong2
pw useradd -n $IO_USER -c "User for yunkong2" -b /usr/local/www -g yunkong2 -s /usr/sbin/nologin -w none

#Set rights
echo "Set permissions..."
chmod 755 /usr/local/etc/rc.d/yunkong2
chmod 755 /usr/local/bin/yunkong2
chown -R $IO_USER @@PATH@@/../../

#Replace user yunkong2 with current user
#sed -i -e "s/yunkong2USER=.*/yunkong2USER=$IO_USER/" /usr/local/etc/rc.d/yunkong2
NODE=${NODE//\//\\/}
sed -i -e s/command=.*/command=$NODE/ /usr/local/etc/rc.d/yunkong2
chown root:wheel /usr/local/etc/rc.d/yunkong2
sysrc yunkong2_enable=YES

# Start the service!
echo "Start yunkong2..."
service yunkong2 start
echo "call http://ip_address:8081/ in browser to get the AdminUI of yunkong2"
