#!/bin/bash
set -e


log() {
    if [[ "TRACE" = "$1" ]] || [[ `(echo "TRACEDEBUGINFOERRORWARN" |sed s/^.*"TRACE"//g )` == *"$1"* ]]; then
        echo "`date '+%Y-%m-%d %H:%M:%S'` $1: $2"
    fi;
}

trim() {
    echo -e "${1}" | tr -d '[[:space:]]'
}
isEmpty() {
    if [[ -z "$(trim "$1")" ]] || [[ -z "$1" ]]; then
        true
    else
        false
    fi;
}

check_exist_certificate(){
    local CERTIFICATE_DIRECTORY="/etc/docker/certs.d"
    if [ -d "$CERTIFICATE_DIRECTORY" ] ;
        then
            log INFO "Directory $CERTIFICATE_DIRECTORY exists."
        else
            log ERROR "Error: Directory with certificate $CERTIFICATE_DIRECTORY not found. Install delivery app stopped."
            exit 1
    fi

    local CERTIFICATE_ARTIX_DIRECTORY="$CERTIFICATE_DIRECTORY/dockerregistry.artix.su:2443"

    if [ -d "$CERTIFICATE_ARTIX_DIRECTORY" ] ;
        then
            log INFO "Directory $CERTIFICATE_ARTIX_DIRECTORY exists."
        else
            log ERROR "Error: Certificate artix not added. Add certificate. Install delivery app stopped."
            exit 1
    fi
}

verify_artix_certificate(){
    local TARGET="dockerregistry.artix.su";
    log INFO "Verify expiration certificate for $TARGET";
    local expirationdate=$(date -d "$(: | openssl s_client -connect $TARGET:2443 -servername $TARGET 2>/dev/null \
                              | openssl x509 -text \
                              | grep 'Not After' \
                              |awk '{print $4,$5,$7}')" '+%s');

    local current_day=$(date +%s);
    if [ $current_day -gt $expirationdate ]; then
        log ERROR "Certificate for $TARGET expires on $(date -d @$expirationdate '+%Y-%m-%d')"
        exit 1;
    else
        log INFO "Certificate expires on $expirationdate";
    fi;
}

check_exist_certificate;
verify_artix_certificate;


log INFO "Start install apt-transport-https, ca-certificates, curl, software-properties-common"

apt-get update
apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    software-properties-common

vrelease=$(lsb_release -cs)
vid=$(lsb_release -is)
vid=${vid,,}

log INFO "Add repository deb [arch=amd64] https://download.docker.com/linux/$vid $vrelease stable"
curl -fsSL https://download.docker.com/linux/$vid/gpg | gpg --dearmor > /etc/apt/trusted.gpg.d/docker.gpg -
add-apt-repository -n \
   "deb [arch=amd64] https://download.docker.com/linux/$vid \
   $vrelease \
   stable"

log INFO "apt-get update"

apt-get update

log INFO "Start install docker-ce"

apt-get install -y docker-ce
