#!/bin/bash

### SYSTEM SETUP
rex doas mkdir -p /4server
rex doas chmod 777 /4server
rex doas chown 4server:4server /4server
rex mkdir -p /4server/data/log
template templates/hosts /etc/hosts

### BACKUP DIR
rex doas mkdir -p /BACKUP
rex doas chmod 777 /BACKUP
rex doas chown 4server:4server /BACKUP


### TMP DIR
rex doas mkdir -p /4server/tmp
rex doas chmod 777 /4server/tmp
rex doas chown 4server:4server /4server/tmp



template templates/.profile /home/4server/.profile

### PACKAGES
template templates/repositories /etc/apk/repositories
rex "doas apk update && doas apk upgrade"
rex doas apk add sshfs borgbackup iperf linux-lts openssh ufw python3 build-base python3-dev linux-headers py3-pip gcc g++ musl-dev libffi-dev make jq rsync mc vim docker docker-compose htop linux-lts sqlite bash postgresql16-client

rex doas pip install --root-user-action ignore --break-system-packages --no-cache-dir "uvicorn[standard]" fastapi pydantic psutil gdown

### own bins
echo "Running prsync ./sbin"
prsync -h "/app/host_vars/hosts" -avz ./sbin/ /4server/sbin/

### POSTGRESS
rex mkdir -p /4server/data/postgres/etc
template templates/pq_hba.conf /4server/data/postgres/etc/




### API

#INSTALL API KEYS
template templates/4server /etc/4server
rex doas chown root:root /etc/4server
rex doas chmod 600 /etc/4server

#INSTALL API SERVICE
template templates/init.d/api /etc/init.d/api
rex doas chmod 0755 /etc/init.d/api
rex doas chown root:root /etc/init.d/api
rex doas rc-update add api default
rex doas rc-service api restart

#INSTALL checkCalls SERVICE
template templates/init.d/checkCalls /etc/init.d/checkCalls
rex doas chmod 0755 /etc/init.d/checkCalls
rex doas chown root:root /etc/init.d/checkCalls
rex doas rc-update add checkCalls default
rex doas rc-service checkCalls restart

#INSTALL cleanTmp SERVICE
template templates/init.d/cleanTmp /etc/init.d/cleanTmp
rex doas chmod 0755 /etc/init.d/cleanTmp
rex doas chown root:root /etc/init.d/cleanTmp
rex doas rc-update add cleanTmp default
rex doas rc-service cleanTmp restart

#INSTALL cpu service
template templates/init.d/cpu /etc/init.d/cpu
rex doas chmod 0755 /etc/init.d/cpu
rex doas chown root:root /etc/init.d/cpu
rex doas rc-update add cpu default
rex doas rc-service cpu restart

### Infrastructure
##### Docker
rex doas rc-service docker start
rex doas rc-update add docker default
rex doas rc-update del docker boot

#LOGIN ODOO4PROJECTS DOCKER REPO
rex "echo 'Airbus12docker' | doas docker login docker.odoo4projects.com -u admin --password-stdin"


rex mkdir -p /4server/data/traefik/etc
template templates/traefik.yaml /4server/data/traefik/etc/traefik.yaml

rex mkdir -p /4server/data/traefik/etc/certs
echo "prsync traefik certs"
prsync -h "/app/host_vars/hosts" -avz ./etc/traefik/certs/* /4server/data/traefik/etc/certs/

template templates/docker-compose.yml /4server/docker-compose.yml
rex doas docker-compose -f /4server/docker-compose.yml up -d --force-recreate
