#!/bin/bash

top_dir=$(pwd)

. ./functions

export TC_HOME="/home/tc"
export TC_DEPS="$top_dir/3rdparty"

if [ "${top_dir##$TC_HOME}" != $top_dir ]; then
    print_error "Cannot start TC installation, try other directory besides $TC_HOME"
    exit 1
fi

if [ ! -e $TC_DEPS ]; then
    print_error "TC dependencies are missing in $TC_DEPS"
    exit 1
fi

# customize system commands in shell
cp='command cp --verbose --archive --remove-destination'
mv='command mv --verbose --force'
mkdir='command mkdir --verbose --parents'

export cp mv mkdir

# prepare assets dir for web
mkdir --parents "$TC_DEPS/web/assets"
cp -a "$TC_DEPS/web/bootbox-4.4.0.min.js" "$TC_DEPS/web/assets/bootbox.min.js"
cp -a "$TC_DEPS/web/chart.bundle.min.js" "$TC_DEPS/web/assets/chart.bundle.min.js"
tmp_dir="$TC_DEPS/web/temp"

mkdir --parent $tmp_dir
tar zxf "$TC_DEPS/web/bootstrap-3.3.6.tar.gz" -C $tmp_dir --strip-components=1
cp -a "$tmp_dir/dist" "$TC_DEPS/web/assets/bootstrap"
rm -rf $tmp_dir

mkdir --parent $tmp_dir
tar zxf "$TC_DEPS/web/jquery-1.12.4.tar.gz" -C $tmp_dir --strip-components=1
cp -a "$tmp_dir/dist/jquery.min.js" "$TC_DEPS/web/assets/jquery.min.js"
rm -rf $tmp_dir

#######################################################################
#
# Installation Beginning
#
#######################################################################

exec 3>&1 #save the stdout

exec 1>>${INSTALL_LOGFILE} #all stdout is directs to the log file
exec 2>>${INSTALL_LOGFILE} #all stderr is directs to the log file
print_info "Installation log: $INSTALL_LOGFILE"


if [ -f /etc/redhat-release ]; then
    osver=$(head -n 1 /etc/redhat-release)
    # removing tailing line ending
    osver=${osver%%)*}
    osver="$osver)"
    print_info "Server: $osver"
    target="CentOS Linux release 7.4.1708 (Core)"
    if [ "$osver" == "$target" ]; then
        cd centos7
        /bin/bash ./install $@
    else
        print_error "$osver is not supported"
        exit 1
    fi
else
    print_error "Only CentOS is supported"
    exit 1
fi

# for backup upload
mkdir -p /home/tcharbor
chown -R daemon:daemon /home/tcharbor

# install prebuilt binaries for tftpboot, bzImage and rootfs.tar.gz
fw_file="$top_dir/client/tc_firmware"
gpg2 --decrypt --output "$fw_file.tar" --no-tty --batch --quiet --passphrase "tc-firmware" "$fw_file"
tar xmf "$fw_file.tar" -C "$TC_HOME/tftpboot"
rootfs="$TC_HOME/tftpboot/rootfs"
mkdir $rootfs
cd $rootfs
cp ../rootfs.cpio.gz .
gunzip rootfs.cpio.gz
cpio -id --file=rootfs.cpio
cd ..
cp rootfs/usr/share/boot/bzImage .
rm -rf rootfs
chmod +x bzImage
chmod +x rootfs.cpio.gz

echo "" 1>&3

exec 1>&3
exec 3>&-

exit 0

