#!/bin/bash


download_liner() {
    platform=linux
    os_name=$(uname -s | tr '[:upper:]' '[:lower:]')
    case "$os_name" in
        "darwin")
            platform="darwin"
            ;;
        "linux")
            platform="linux"
            ;;
        "cygwin"|"msys"|"mingw"*)
            platform="windows"
            ;;
        *)
            echo "unspported platform $os_name"
            exit 1
            ;;
    esac


    arch=amd64
    case $(uname -m) in
        aarch64|arm64)
            arch=arm64;;
        arm*)
            arch=armv7;;
    esac

    if type -p curl; then
    getcurl="curl -sSLf"
    else
        getcurl="wget -O-"
    fi

    checksum=$($getcurl https://github.com/phuslu/liner/releases/download/v0.0.0/checksums.txt | grep -E "liner_${platform}_${arch}-[0-9]+.tar.gz")
    filename=$(echo $checksum | awk '{print $2}')

    echo "downloading $filename ..."
    if type -p curl; then
        curl -L https://github.com/phuslu/liner/releases/download/v0.0.0/$filename > $filename
    else
        wget https://github.com/phuslu/liner/releases/download/v0.0.0/$filename -O $filename
    fi

    if test "$(sha1sum $filename || shasum $filename)" != "$checksum"; then
        echo "$filename sha1sum mismatched, please check your network!"
        rm -rf $filename
        exit 1
    fi
    if test -x liner; then
        echo liner | tar xvzf $filename -T -
        rm -rf $filename
        exit 0
    fi
}

update_server() {
    local bin="liner"

    local ver=$($bin -version 2>&1)
    SERVER_LIST=(
        liner_srv,liner-config,
    )

    local REMOTE_USER="root"
    local REMOTE_DIR="~/liner"

    for line in "${SERVER_LIST[@]}"; do
        IFS=',' read -r hostname env_name1 env_name2 <<< "$line"

        service="liner@${env_name1}"

        echo "Updating $hostname $(echo $service) to v$ver ..."
        rsync -azP "$bin" "${hostname}:${REMOTE_DIR}/"
        echo "==> copy $bin to $hostname:$REMOTE_DIR done"

        ssh ${hostname} "rm -fv ${REMOTE_DIR}/log/${env_name1}*.log"
        ssh ${REMOTE_USER}@${hostname} "systemctl restart $service"
        echo "==> Update to $hostname:liner@$env_name1.yaml done"

        if [ -n "$env_name2" ]; then
            sleep 2
            service="liner@${env_name2}"

            ssh ${hostname} "rm -fv ${REMOTE_DIR}/log/${env_name2}*.log"
            ssh ${REMOTE_USER}@${hostname} "systemctl restart $service"
            echo "==> Update to $hostname liner@$env_name2.yaml done"
        fi
    done
}
download_liner
# update_server
