#!/bin/bash
# Info: Script to install/create service pod_repo
# Author: JesusPerezLorenzo 
# Release: 1.0
# Date: 19-11-2023

ROOT_DATA=${ROOT_DATA:-/data}
DATA_REPO=${DATA_REPO:-$ROOT_DATA/repo}
DATA_DOC=${DATA_DOC:-$ROOT_DATA/doc}
DATA_DBS=${DATA_DBS:-$ROOT_DATA/dbs}
DATA_WEBHOOKS=${DATA_WEBHOOKS:-$ROOT_DATA/webhooks}

ROOT_SOURCE=$(dirname "$0")

exit 1
sudo mkdir -p $ROOT_DATA
sudo chown -R $(id -u):$(id -g)  $ROOT_DATA

if [ ! -r "env" ] ; then 
	echo "# Env settings " >env
	echo "DATA_REPO=$DATA_REPO" >>env
	echo "DATA_DOC=$DATA_DOC" >>env
	echo "DATA_DBS=$DATA_DBS" >>env
fi

if [ ! -d "$DATA_REPO" ] && [ -r "$ROOT_SOURCE/data.tar.gz" ] ; then 
   sudo tar -C / -xzf "$ROOT_SOURCE/data.tar.gz" && echo "Data Services installed !"
else
	sudo mkdir -p $DATA_REPO/gitea/conf
	sudo mkdir -p $DATA_DOC
	sudo mkdir -p $DATA_DBS
fi

hostname=$(hostname -s)
id=$(id -u)

if [ -r "gitconfig" ] ; then 
   [ ! -r "$HOME/.gitconfig" ] && cp gitconfig "$HOME/.gitconfig" 
   [ -d "/home/devadm" ] && [ ! -r "/home/devadm/.gitconfig" ] && sudo cp gitconfig "/home/devadm/.gitconfig"  && sudo chown devadm "/home/devadm/.gitconfig"
fi

[ ! -d "/dao/$hostname/services/pod_repo" ] && sudo mkdir -p "/dao/$hostname/services/pod_repo"  

sudo chown -R $id /dao  

cp -pr *  "/dao/$hostname/services/pod_repo"

cd  "/dao/$hostname/services/pod_repo"  || exit 1

if [ -r "gitea/full_app.ini" ] && [ ! -r "$DATA_REPO/gitea/conf/app.ini" ] ; then
   cp gitea/full_app.ini "$DATA_REPO/gitea/conf/app.ini"
fi

if [ ! -r "app.ini" ] ; then 
   ln -s $DATA_REPO/gitea/conf/app.ini . 
fi

# [ -r "bin/apply.sh" ] && ./bin/apply.sh 

# Add systemd service
sudo cp pod-repo.service /lib/systemd/system
sudo systemctl daemon-reload
sudo systemctl enable pod-repo.service
sudo systemctl restart pod-repo.service

if [ -r 'ddeploy_docker-compose.yml' ] ; then 
   mv deploy_docker-compose.yml docker-compose.yml
   val_timeout=10
   wait=10
   echo -n "Waiting services to come up ... "
   while [ -z "$nc_port" ] 
   do 
     if nc -zv -w 1 "10.11.1.10" 3000 >/dev/null 2>/dev/null ; then 
       nc_port=1	
     fi
     if [ -z "$nc_port" ] ; then 
       sleep "$wait"
       num=$((num + wait))
       [ "$val_timeout" -gt  0 ] && [ "$num" -gt "$val_timeout" ] && break
       echo -n "$num "
     fi
   done
   echo ""
   [ -r "gitea/full_app.ini" ] &&  cp gitea/full_app.ini "$DATA_REPO/gitea/conf/app.ini"
   sudo systemctl restart pod-repo.service
fi

# Fix /etc/hosts for repo operations 
sudo sed -i /^10.11.1.10/d /etc/hosts 
sudo sed -i "s/$hostname/$hostname.pub/g" /etc/hosts 
echo "10.11.1.10 $hostname localrepo.cloudnative.zone"  | sudo tee -a /etc/hosts


exit 0

