#!/bin/bash
#set -uo pipefail
#==============================================================#
# File      :   install
# Desc      :   download & install pigsty src
# Ctime     :   2022-10-30
# Mtime     :   2026-01-27
# Path      :   https://repo.pigsty.io/get (global, default)
# Usage     :   curl -fsSL https://repo.pigsty.io/get | bash
# Docs      :   https://pigsty.io/docs/setup/install
# Deps      :   curl
# Author    :   Ruohang Feng (rh@vonng.com)
# License   :   Apache-2.0 @ https://pigsty.io/docs/about/license/
#==============================================================#
DEFAULT_VERSION=v4.0.0

# To install the latest version of pigsty (v4.0.0):
# curl -fsSL https://repo.pigsty.io/get | bash; cd ~/pigsty;
# curl -fsSL https://repo.pigsty.cc/get | bash; cd ~/pigsty;

# To install a specific version of pigsty (e.g. v4.0.0)
# curl -fsSL https://repo.pigsty.io/get | bash -s v4.0.0
# curl -fsSL https://repo.pigsty.cc/get | bash -s v4.0.0

#--------------------------------------------------------------#
# Log Util
#--------------------------------------------------------------#
# if output is a terminal, setup color alias, else use empty str
if [[ -t 1 ]]; then
    __CN='\033[0m';__CK='\033[0;30m';__CR='\033[0;31m';__CG='\033[0;32m';
    __CY='\033[0;33m';__CB='\033[0;34m';__CM='\033[0;35m';__CC='\033[0;36m';__CW='\033[0;37m';
else
    __CN='';__CB='';__CR='';__CG='';__CY='';__CB='';__CM='';__CC='';__CW='';
fi
function log_info()  { printf "[${__CG} OK ${__CN}] ${__CG}$*${__CN}\n"; }
function log_warn()  { printf "[${__CY}WARN${__CN}] ${__CY}$*${__CN}\n"; }
function log_error() { printf "[${__CR}FAIL${__CN}] ${__CR}$*${__CN}\n"; }
function log_red()   { printf "[${__CR}WARN${__CN}] ${__CR}$*${__CN}\n"; }
function log_debug() { printf "[${__CB}HINT${__CN}] ${__CB}$*${__CN}\n"; }
function log_title() { printf "[${__CG}$1${__CN}] ${__CG}$2${__CN}\n";   }
function log_hint()  { printf "${__CB}$*${__CN}\n"; }
function log_line()  { printf "${__CM}[$*] ===========================================${__CN}\n"; }


#--------------------------------------------------------------#
# Version
#--------------------------------------------------------------#
# arg1 > env > default
if [[ -n "$1" ]]; then
    VERSION="$1"
    VERSION_FROM="arg"
elif [[ -n "${PIGSTY_VERSION}" ]]; then
    VERSION="${PIGSTY_VERSION}"
    VERSION_FROM="env"
else
    VERSION=${DEFAULT_VERSION}
    VERSION_FROM="default"
fi


#--------------------------------------------------------------#
# Reference
#--------------------------------------------------------------#
log_line "${VERSION}"
log_hint "$ curl -fsSL https://repo.pigsty.io/get | bash"
log_title "Docs" "https://pigsty.io/docs"
log_title "Demo" "https://demo.pigsty.io"
log_title "Repo" "https://github.com/pgsty/pigsty"

log_line "Download"
log_info "version = ${VERSION} (from ${VERSION_FROM})"


#--------------------------------------------------------------#
# Download
#--------------------------------------------------------------#
SRC_FILENAME="pigsty-${VERSION}.tgz"
DOWNLOAD_TO="/tmp/${SRC_FILENAME}"
DOWNLOAD_URL="https://repo.pigsty.io/src/${SRC_FILENAME}"

# download file from url, if file already exists with same size, skip download
function download_file(){
    local data_url=$1
    local data_file=$2

    log_hint "curl -fSL ${data_url} -o ${data_file}"
    # if file exists and have the exact same size, just use it and skip downloading
    if [[ -f ${data_file} ]]; then
        if [[ "$(uname)" == "Darwin" ]]; then
            size=$(stat -f %z "${data_file}")
        else
            size=$(stat -c %s "${data_file}")
        fi
        curl_size=$(curl -fsLI ${data_url} | grep -i 'Content-Length' | awk '{print $2}' | tr -d '\r')
        if [[ ${size} -eq ${curl_size} ]]; then
        log_warn "tarball = ${data_file} exists, size = ${size}, use it"
        #log_hint "rm -rf ${data_file};  # remove it to redownload source tarball"
        return 0
        fi
    fi
    curl -# -fSL ${data_url} -o ${data_file}
    return $?
}

download_file "${DOWNLOAD_URL}" "${DOWNLOAD_TO}"
if [[ $? -ne 0 ]]; then
    log_error "fail to download pigsty source from ${DOWNLOAD_URL}"
    log_hint "check: https://pigsty.io/docs/setup"
    log_hint "alternative url: ${SECONDARY_SRC_URL}"
    exit 2
fi
log_info "md5sums = $(md5sum ${DOWNLOAD_TO})"


#--------------------------------------------------------------#
# Install
#--------------------------------------------------------------#
INSTALL_TO="${HOME}/pigsty"
INSTALL_DIR=$(dirname ${INSTALL_TO})

log_line "Install"
if [[ $(whoami) == "root" ]]; then
    log_warn "os user = root , it's recommended to use a non-root sudo-able admin"
fi

# extract to home dir if ~/pigsty not exists
if [[ ! -d ${INSTALL_TO} ]]; then
    log_info "install = ${INSTALL_TO}, from ${DOWNLOAD_TO}"
    tar -xf "${DOWNLOAD_TO}" -C "${INSTALL_DIR}";
else
    log_warn "pigsty already installed on '${INSTALL_TO}', if you wish to overwrite:"
    log_hint "sudo rm -rf /tmp/pigsty_bk; cp -r ${INSTALL_TO} /tmp/pigsty_bk; # backup old"
    log_hint "sudo rm -rf /tmp/pigsty;    tar -xf ${DOWNLOAD_TO} -C /tmp/; # extract new"
    log_hint "rsync -av --exclude='/pigsty.yml' --exclude='/files/pki/***' /tmp/pigsty/ ${INSTALL_TO}/; # rsync src"
fi


#--------------------------------------------------------------#
# Bootstrap
#--------------------------------------------------------------#
# check ansible is installed
log_line "Bootstrap"
if command -v ansible-playbook >/dev/null ; then
    log_info "ansible = ready"
    log_info "bootstrap = skip"
    log_hint "you can run ./bootstrap to extrac offline package and install ansible"
else
    log_warn "ansible = not found, bootstrap"
    cd "${INSTALL_TO}"
    ./bootstrap
fi

#--------------------------------------------------------------#
# Next Hint
#--------------------------------------------------------------#
log_line "What's Next"
log_hint "cd ${INSTALL_TO}"
log_hint './configure      # [OPTIONAL] preflight-check and config generation'
log_hint './deploy.yml     # deployment everything described by your config'

