#!/bin/bash
#
# Redis Service

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
. /etc/federated
get_appvars

config_redis() {
  echo -ne "* Configuring redis container.."

  if [ ! -d "/federated/apps/redis" ]; then
    mkdir -p /federated/apps/redis/data/bitnami/redis/data
    chown -R 1001 /federated/apps/redis/data/bitnami/redis
  fi

cat > /federated/apps/redis/docker-compose.yml <<EOF
services:
  redis:
    image: bitnami/redis:\${IMAGE_VERSION}
    container_name: redis
    hostname: redis.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.45
    env_file:
      - ./.env
    volumes:
      - ./data/bitnami/redis/data:/bitnami/redis/data

networks:
  core:
    external: true
EOF

REDIS_SECRET=$(create_password);

cat > /federated/apps/redis/.env <<EOF
IMAGE_VERSION="$(current_version redis)"
REDIS_PASSWORD=$REDIS_SECRET
EOF
chmod 600 /federated/apps/redis/.env

sysctl "vm.overcommit_memory=1" &> /dev/null

echo -ne "done.\n"
}
start_redis() {
  # Start service with command to make sure it's up before proceeding
  start_service "redis" "nc -z 192.168.0.45 6379 &> /dev/null" "7"

  echo -ne "done.\n"
}
uninstall_redis() {
  # First stop the service
  cd /federated/apps/redis && docker compose -f docker-compose.yml -p redis down &> /dev/null

  # Delete the app directory
  rm -rf /federated/apps/redis

  echo -ne "done.\n"
}
