#!/bin/bash

OS_TYPE=`uname`
ACCESS_KEY=$1
SERVER_IP=$2
CONF="/usr/whatap/infra/conf/whatap.conf"

# 운영체제에 따른 패키지 설치
if [ "$OS_TYPE" = "SunOS" ]; then
    echo "OS : SunOS"
    ZFS_COUNT=`cat /etc/mnttab | grep zfs | wc -l`

    if [ "$ZFS_COUNT" -eq 0 ]; then
        echo "Not using zfs"
    else
        UTILS=("zpool" "zfs")

        for util in "${UTILS[@]}"; do
            if ! command -v "$util" > /dev/null 2>&1; then
                echo "Required command not found"
                echo " - $util"
                echo "Please check your PATH settings."
                echo "PATH : $PATH"
                exit 1
            fi
        done
        echo "Command confirmation completed"
    fi

    PKGADD_CMD=""
    PKGRM_CMD=""

    if command -v pkgadd > /dev/null 2>&1; then
        PKGADD_CMD=`command -v pkgadd`
    elif [ -x /usr/sbin/pkgadd ]; then
        PKGADD_CMD="/usr/sbin/pkgadd"
    else
        echo "Error: pkgadd command not found. Please ensure pkgadd is installed."
        exit 1
    fi

    if command -v pkgrm > /dev/null 2>&1; then
        PKGRM_CMD=`command -v pkgrm`
    elif [ -x /usr/sbin/pkgrm ]; then
        PKGRM_CMD="/usr/sbin/pkgrm"
    else
        echo "Error: pkgrm command not found. Please ensure pkgrm is installed."
        exit 1
    fi


    pkginfo | grep whatap-infra > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        $PKGRM_CMD -n whatap-infra
        if [ $? -ne 0 ]; then
            echo "whatap-infra remove fail"
            exit 1
        fi
    fi

    $PKGADD_CMD -d ./ all
    if [ $? -eq 0 ]; then
        echo "whatap-infra install ok"
    else
        echo "whatap-infra install fail"
        exit 1
    fi

    if [ -f "$CONF" ]; then
        echo "File $CONF exists."
        echo "Do you want to overwrite the file? (y/n):"
        read USER_INPUT

        if [ "$USER_INPUT" = "y" ] || [ "$USER_INPUT" = "Y" ]; then
            CREATED_TIME=`perl -e 'use Time::HiRes qw(gettimeofday); ($seconds, $microseconds) = gettimeofday; print ($seconds * 1000 + int($microseconds / 1000)), "\n";'`
            rm $CONF
            echo "license=$ACCESS_KEY" | tee $CONF
            echo "whatap.server.host=$SERVER_IP" | tee -a $CONF
            echo "createdtime=$CREATED_TIME" | tee -a $CONF
        else
            echo "File not deleted."
        fi
    else
        CREATED_TIME=`perl -e 'use Time::HiRes qw(gettimeofday); ($seconds, $microseconds) = gettimeofday; print ($seconds * 1000 + int($microseconds / 1000)), "\n";'`
        echo "license=$ACCESS_KEY" | tee $CONF
        echo "whatap.server.host=$SERVER_IP" | tee -a $CONF
        echo "createdtime=$CREATED_TIME" | tee -a $CONF
    fi

    echo "Install Complete."
else
    echo "Unsupported OS: $OS_TYPE"
    exit 1
fi
