#!/bin/bash
#
#
#

# plz be careful when comment exit-statement!!!!
exit

NEW_HARBOR_VERSION='v2.4.1'
DOWNLOAD_DEST_DIR='/tmp'
DOWNLOAD_DEST_FILE="${DOWNLOAD_DEST_DIR}/harbor-online-installer-${NEW_HARBOR_VERSION}.tgz"
SMARDIGO_HOME="{{ service_base_path }}/{{ inventory_hostname }}"
HARBOR_BACKUP_DIR="/opt/harbor_bkp_dir"

echo "downloading trabll with new harbor version"
wget https://github.com/goharbor/harbor/releases/download/${NEW_HARBOR_VERSION}/harbor-online-installer-${NEW_HARBOR_VERSION}.tgz -O ${DOWNLOAD_DEST_FILE}

echo "docker pull harbor-migration image"
docker pull goharbor/prepare:${NEW_HARBOR_VERSION}

echo "Stopping harbor..."
cd ${SMARDIGO_HOME}/harbor
docker-compose down

if [ ! -d ${HARBOR_BACKUP_DIR} ]; then
  echo "saving old install dir + pg-data-dir"
  cd ${SMARDIGO_HOME}
  mkdir -p ${HARBOR_BACKUP_DIR}
  mv "${SMARDIGO_HOME}/harbor" ${HARBOR_BACKUP_DIR}/
  cp -r /data/database ${HARBOR_BACKUP_DIR}/
else
  echo "backup dir << ${HARBOR_BACKUP_DIR} >> for old harbor installtion detected. ply removed before proceeding"
  exit 
fi

echo "unpacking tarball new harbor version..."
tar -xzf ${DOWNLOAD_DEST_FILE} -C ${SMARDIGO_HOME}

echo "copy harbor.yml for upgrade-prepare step"
cp ${HARBOR_BACKUP_DIR}/harbor/harbor.yml ${SMARDIGO_HOME}/harbor/harbor.yml

echo "running docker container for harbor-migration to version: $NEW_HARBOR_VERSION ..."
docker run -it --rm -v /:/hostfs goharbor/prepare:${NEW_HARBOR_VERSION} migrate -i ${SMARDIGO_HOME}/harbor/harbor.yml

echo "starting harbor installation ..."
${SMARDIGO_HOME}/harbor/install.sh --with-trivy --with-chartmuseum
