#!/bin/bash
# Info: Script to install oras
# Author: JesusPerezLorenzo  
# Release: 1.0 
# Date: 11-01-2024

USAGE="install-oras-os.sh "
[ "$1" == "-h"  ] && echo "$USAGE"  && exit 1
ORG=$(dirname "$0")

ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')"
OS="$(uname | tr '[:upper:]' '[:lower:]')"

_install_oras() {
    local curr_version
    [ -z "$VERSION" ] && echo "VERSION not found" && exit  1
    if [ -x "/usr/local/bin/oras" ] ; then
       cur_version=$(/usr/local/bin/oras version | grep "Version" | cut -f2 -d":" | sed "s/ //g")
    else
       curr_version=0
    fi
    if [ "$curr_version" != "$VERSION" ] ; then  
        curl -fsSLO "https://github.com/oras-project/oras/releases/download/v${VERSION}/oras_${VERSION}_${OS}_${ARCH}.tar.gz"
        mkdir -p oras-install/
        tar -zxf "oras_${VERSION}_${OS}_${ARCH}.tar.gz" -C oras-install/
        sudo mv oras-install/oras /usr/local/bin/
        rm -rf "oras_${VERSION}_${OS}_${ARCH}.tar.gz" oras-install/
    fi
}

_config_oras() {
    if [ -r "$ORG/docker-config" ] ; then 
      [ ! -d "$HOME/.docker" ] && mkdir $HOME/.docker
      base64 -d < "$ORG/docker-config" | sudo tee $HOME/.docker/config.json >/dev/null
    fi
    if [ -r "$ORG/zli-cfg" ] ; then 
        cp "$ORG/zli-cfg" "$HOME/.zot"
    fi
}

[ -r "./env-oras"  ] && . ./env-oras

# Update and add packages to installation
[ -z "$1" ] || [ "$1" == "install" ] && _install_oras
[ -z "$1" ] || [ "$1" == "config" ] && _config_oras
