#!/bin/bash
#
# Copyright (c) 2014-2016 by Cisco Systems, Inc.
# All rights reserved.

# app_install script
# Script to initialize the local rpm repository and installing 
# local RPMs.
#

YUM=/usr/bin/yum
CREATEREPO=/usr/share/createrepo/genpkgmetadata.py

if [ -f "/pkg/etc/app_repo.txt" ]; then
    APP_REPO_DIR=`cat /pkg/etc/app_repo.txt`
else
    APP_REPO_DIR="/misc/disk1/apprepo-dont-delete"
fi


LOCAL_YUM_REPO=$APP_REPO_DIR/localrepo
LOCAL_RPM_REPO=$APP_REPO_DIR/rpms
CONFIGS_DIR=$APP_REPO_DIR/configs
IGNORE_APP_REPO=$APP_REPO_DIR/.ignore

YUM_REPO_CONF=/etc/yum/repos.d/localrpmdb.repo
YUM_CONF_FILE=/etc/yum/yum.conf
YUM_PLUGIN_CONF_FILE=/etc/yum/pluginconf.d/rpm-persistence.conf
APP_INSTALL_SENTINEL_FILE=/etc/yum/.appinstall.done


# pick up the right python
export PATH=/usr/bin:$PATH



function main()
{
    check_for_system_upgrade

    if [ ! -d "$APP_REPO_DIR" ]; then

        create_app_repo_dir

        if [ "$?" -ne "0" ]; then
            echo "Error occurred in creating the app-repo-dir."
            echo "Third party application installed by the user cannot be stored in app-repo"
            exit 1
        fi

        
    elif [ -f "$IGNORE_APP_REPO" ]; then

        echo "$IGNORE_APP_REPO: ignore-app-repo file exists, third party apps are not reinstalled."
        echo "You can remove the $IGNORE_APP_REPO file and run /pkg/bin/app_install script to install third party apps."

    elif [ -f "$APP_INSTALL_SENTINEL_FILE" ] && [ -z "$FORCE_APP_INSTALL" ];  then

        echo """
XR disk is not formatted from last time, so we dont need to run app_install.
If you want to run the app_install any way, you can run as
FORCE_APP_INSTALL=1 /pkg/bin/app-install
"""

    else

        do_app_install 

    fi

    # Finally enable yum-plugins so that third-party app's installed get stored
    # in app-repo.

    enable_yum_plugins
    touch $APP_INSTALL_SENTINEL_FILE

}

# check_for_system_upgrade
# if system is upgraded we might not be able to use the app-repo created for
# previous version. So we will move the apprepo for the previous version to
# apprepo-<version> dir under /misc/disk1 and create a new apprepo for current
# version.

function check_for_system_upgrade
{
    test -d "$APP_REPO_DIR" || return

    XR_VERSION=`grep version /etc/build-info.txt 2>/dev/null`
    APP_REPO_VERSION=`grep version $APP_REPO_DIR/build-info.txt 2>/dev/null`

    if [ "$XR_VERSION" == "$APP_REPO_VERSION" ]; then
        return 
    fi

    if [ -z "$APP_REPO_VERSION" ]; then
        APP_REPO_VERSION='None'
    fi

    echo "XR_VERSION = $XR_VERSION"
    echo "APP_REPO_VERSION = $APP_REPO_VERSION"
    echo "No third party apps gets installed as XR and APP_REPO version didn't match"

    set -x
    mv $APP_REPO_DIR `dirname $APP_REPO_DIR`/apprepo-$APP_REPO_VERSION
    set +x
 
}

# do_app_install:
# Install the third party packages from the apprepo.

function do_app_install 
{
    # update the app-repo yum database.
    update_yumdb

    # if we could not properly update the repo database then we will use rpm to
    # install the packages. Otherwise we will use yum to do the work.
    if [ "$?" -eq "0" ]; then
        create_yum_repo_conf_file
        do_install_yum_packages || rc=1
    else
        echo "Updating the app-repo db failed. Installing the yum packages using RPM"
        do_install_rpms $LOCAL_YUM_REPO || rc=1
    fi

    # Install any rpms that user installed using 'rpm' command directly.
    do_install_rpms $LOCAL_RPM_REPO || rc=1

    # copy previously stored configuration files.
    copy_stored_config_files || rc=1

    return $rc
}

# create_app_repo_dir and other subdirs.
function create_app_repo_dir
{
    mkdir -p $APP_REPO_DIR 

    if [ $? -ne "0" ]; then
        echo "ERROR: $APP_REPO_DIR: unable to create the directory"
        return 1
    fi

    # save the version info in the APP-REPO
    cp /etc/build-info.txt $APP_REPO_DIR || return 1

    test -d $LOCAL_RPM_REPO || mkdir -m 755 -p $LOCAL_RPM_REPO || return 1
    test -d $LOCAL_YUM_REPO || mkdir -m 755 -p $LOCAL_YUM_REPO || return 1
    test -d $CONFIGS_DIR    || mkdir -m 755 -p $CONFIGS_DIR    || return 1

    echo "Created the app-repo."

}

# install all the rpm's directly using rpm commands. 
# we use this if we have issue with localrepo/user installed the rpm directly
# using rpm command and manaully copied to the LOCAL_RPM_REPO

function do_install_rpms
{
    local rc=0
    REPO=$1

    echo "Installing rpms from $REPO."
    for rpm in `ls $REPO/*.rpm 2>/dev/null`; do

        cmd="rpm --nodeps -iv $rpm"
        echo "Installing $rpm: $cmd"
        $cmd 

        if [ ${PIPESTATUS[0]} -eq 0 ]; then
            echo "$rpm installation successful." 
        else
            echo "ERROR: $rpm installation failed." 
            rc=1
        fi

    done
    echo "Installing rpms from $REPO completed."

    return $rc
}

do_install_yum_packages()
{
    local rc=0

    echo "Installing yum packages from app-repo"

    for pkg in `(cd $LOCAL_YUM_REPO && ls -t *.rpm 2>/dev/null)` ; do
        # Changing the path to App-Local repo for yum install
	cd $LOCAL_YUM_REPO
	echo $YUM install --disablerepo="*" --enablerepo="localdb" -y $pkg 
        $YUM install --disablerepo="*" --enablerepo="localdb" -y $pkg
    done

    return $rc

}

update_yumdb()
{
    cmd="python $CREATEREPO --update $LOCAL_YUM_REPO"
    echo "$cmd"
    $cmd || return 1

}

create_yum_repo_conf_file()
{
    if [ -e "$YUM_REPO_CONF" ]; then
        return
    fi

    cat > $YUM_REPO_CONF << EOF
[localdb]
name=Local RPM Database
baseurl=file://$LOCAL_YUM_REPO
enabled=1
gpgcheck=0
metadata_expire=0
cost=500
EOF

}

function enable_yum_plugins
{
    if grep enabled=1 $YUM_PLUGIN_CONF_FILE >& /dev/null; then
        echo "Yum rpm-persistence plugin is already enabled. Nothing to do."
        return 
    fi

    echo "Enabling yum plugins for rpm-persistence"

    DIR=`dirname $YUM_PLUGIN_CONF_FILE`
    mkdir -p $DIR

    yum_plugins_path="/pkg/lib/yum-plugins"

    # if pluginpath itself is not defined in the configuration file, add
    # our path to the end of the file.
    # if plugin path is already defined, add it to the same line at the end.

    if ! grep "pluginpath=" $YUM_CONF_FILE >& /dev/null; then
        echo "pluginpath=/pkg/lib/yum-plugins" >> $YUM_CONF_FILE
    else
        sed -i '/pluginpath=/ s?$? /pkg/lib/yum-plugins?' $YUM_CONF_FILE
    fi

    echo -e "[main]\nenabled=1\ndebug_enabled=0\n" > $YUM_PLUGIN_CONF_FILE

    echo "Done."
}

function copy_stored_config_files
{
    local rc=0

    for file in `cd $CONFIGS_DIR && find . -type f` ; do

        CONFIG_FILE=$CONFIGS_DIR/$file
        ROOT_FS_FILE=/$file

        if [ "$CONFIG_FILE" -nt "$ROOT_FS_FILE" ]; then
            echo "cp $CONFIG_FILE $ROOT_FS_FILE"
            cp $CONFIG_FILE $ROOT_FS_FILE || rc=1
        fi

    done

    return $rc
}



## 
main
