#!/bin/bash

alias rm='/bin/rm --preserve-root'

print_help()
{
    echo "Usage: ./ndd-package.sh [command] [package]"
    echo ""
    echo "Commands: install, force-install, remove"
}

if [ -z $1 ]; then
    echo "Command is missing"
    print_help
    exit 1
elif [ -z $2 ]; then
    echo "Package name is missing"
    print_help
    exit 1
fi

PACKAGE_NAME=$2
PACKAGE_CACHE_FOLDER=/etc/ndd-packages/$PACKAGE_NAME

if [ $1 == "install" ] || [ $1 == "force-install" ]; then
    if [ -z $PACKAGE_SOURCE ]; then
        PACKAGE_SOURCE=https://packages-orbix.ndd.tech/generic-linux
    fi

    if [ -z $3 ]; then
        VERSION=current
    else
        echo -n $3 | grep -w '[0-9]\+\.[0-9]\+\.[0-9]\+'
        if [ $? -ne 0 ]; then
            echo "Invalid version number"
            exit 1
        fi
        VERSION=$3
    fi

    #Create temporary work directory
    TMP_DIR=$(mktemp -d -t ci-XXXXXXXXXX)
    if [ $? -ne 0 ]; then
        echo "Failed to create temp install folder"
        exit 1
    fi

    #Auto-remove TMP_DIR
    trap 'rm -rf "$TMP_DIR"' EXIT

    cd $TMP_DIR

    KEYRINGS_PATH=/usr/share/keyrings/

    if [ ! -d $KEYRINGS_PATH ]; then
        mkdir $KEYRINGS_PATH
    fi

    KEY_PATH=$KEYRINGS_PATH/ndd.public
    #Download the NDD's signing key
    if [ ! -f $KEY_PATH ]; then
        echo "Downloading NDD's signing key"
        wget -O /usr/share/keyrings/ndd.public.tmp $PACKAGE_SOURCE/ndd.public
        if [ $? -ne 0 ]; then
            echo "Failed to download public key"
            exit 1
        fi

        mv /usr/share/keyrings/ndd.public.tmp $KEY_PATH
    else
        echo "Using cached public key"
    fi

    #Download the package
    echo "Downloading package"
    PACKAGE=$VERSION.sig
    wget $PACKAGE_SOURCE/$PACKAGE_NAME/$PACKAGE
    if [ $? -ne 0 ]; then
        echo "Failed to download the package"
        exit 1
    fi

    #Validate package's signature
    gpg --no-default-keyring -f $KEY_PATH --verify $PACKAGE
    if [ $? -ne 0 ]; then
        echo "Invalid signature"
        exit 1
    fi

    #Extract package
    TAR_PACKAGE=$VERSION.tar.gz
    gpg --no-default-keyring -f $KEY_PATH --output $TAR_PACKAGE --decrypt $PACKAGE

    tar -xvf $TAR_PACKAGE
    if [ $? -ne 0 ]; then
        echo "Error extracting package"
        exit 1
    fi

    #Load package's metadata
    source ./CONTROL

    if [ -z $BIN_FOLDER ] || [ -z $ETC_FOLDER ] || [ -z $VERSION ]; then
        echo "Invalid CONTROL file"
        exit 1;
    fi 

    #Verify if version is already installed
    if [ -f $PACKAGE_CACHE_FOLDER/CURRENT_VERSION ]; then
        source $PACKAGE_CACHE_FOLDER/CURRENT_VERSION

        if [ $CURRENT_VERSION == $VERSION ] && [ $1 != "force-install" ]; then
            echo "Version $VERSION is already installed"

            exit 0
        fi
    fi

    echo "Installing version $VERSION"

    #Run package specific pre-install script
    if [ -f preinst ]; then
        ./preinst
        if [ $? -ne 0 ]; then
            echo "preinst script failed"
        fi
    fi

    #Install default folders
    mkdir -p $BIN_FOLDER-$VERSION
    if [ $? -ne 0 ]; then
        echo "Error creating install folder"
        exit 1
    fi

    cp -R ./$BIN_FOLDER/* $BIN_FOLDER-$VERSION/
    if [ $? -ne 0 ]; then
        echo "Error copying files"
        exit 1
    fi

    if [ -d $BIN_FOLDER ]; then
        CURRENT_BIN_FOLDER=`readlink -f $BIN_FOLDER`
        rm -f $BIN_FOLDER
    fi

    ln -s $BIN_FOLDER-$VERSION $BIN_FOLDER
    if [ $? -ne 0 ]; then
        echo "Error making symlink"
    fi

    #Copy config files
    if [ ! -d $ETC_FOLDER ]; then
        echo "Creating settings folder"
        mkdir -p $ETC_FOLDER
        if [ $? -ne 0 ]; then
            echo "Error creating install folder"
            exit 1
        fi

        cp -R ./$ETC_FOLDER/* $ETC_FOLDER/
        if [ $? -ne 0 ]; then
            echo "Error copying files"
            exit 1
        fi
    fi

    #Download the latest version of ndd-package.sh
    #This script will be used by the liveupdate
    NDD_PACKAGE_SIG=$PACKAGE_CACHE_FOLDER/ndd-package.sig
    mkdir -p $PACKAGE_CACHE_FOLDER
    wget -O $NDD_PACKAGE_SIG $PACKAGE_SOURCE/ndd-package.sig
    if [ $? -ne 0 ]; then
        echo "Error downloading ndd-package. Liveupdate may not work"
    fi

    #Run package specific post-install script
    if [ -f postinst ]; then
        ./postinst
        if [ $? -ne 0 ]; then
            echo "postinst script failed"
        fi
    fi

    if [ ! -z $CURRENT_VERSION ]; then
        if [ "$BIN_FOLDER-$VERSION" != "$BIN_FOLDER-$CURRENT_VERSION" ] && [ -d $BIN_FOLDER-$CURRENT_VERSION ]; then
            rm -rf $BIN_FOLDER-$CURRENT_VERSION
        fi
    fi
    
    #Make a local cache of the package specific remove scripts
    cp ./CONTROL $PACKAGE_CACHE_FOLDER

    if [ -f prerm ]; then
        cp prerm $PACKAGE_CACHE_FOLDER
    fi

    if [ -f postrm ]; then
        cp postrm $PACKAGE_CACHE_FOLDER
    fi

    chmod -R 500 $PACKAGE_CACHE_FOLDER
    chown -R root:root $PACKAGE_CACHE_FOLDER

    echo "CURRENT_VERSION=$VERSION" > $PACKAGE_CACHE_FOLDER/CURRENT_VERSION
    echo "Installation finished"
	
elif [ $1 == "remove" ]; then
    if [ ! -f $PACKAGE_CACHE_FOLDER/CONTROL ]; then
        echo "Package not found"
        exit 0
    fi

    cd $PACKAGE_CACHE_FOLDER
    source ./CONTROL
    echo "Removing version $VERSION"

    #Run package specific pre-remove script
    if [ -f prerm ]; then
        ./prerm
        if [ $? -ne 0 ]; then
            echo "prerm script failed"
        fi
    fi

    if [ -d $BIN_FOLDER ]; then
        rm -Rf $BIN_FOLDER
    fi

    if [ -d $BIN_FOLDER-$VERSION ]; then
        rm -Rf $BIN_FOLDER-$VERSION
    fi
    
    if [ -d $ETC_FOLDER ]; then
        rm -Rf $ETC_FOLDER
    fi

    #Run package specific post-remove script
    if [ -f postrm ]; then
        ./postrm
        if [ $? -ne 0 ]; then
            echo "postrm script failed"
        fi
    fi

    cd /tmp
    rm -Rf $PACKAGE_CACHE_FOLDER
fi