#!/bin/bash
#
# Vaultwarden Service

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

config_vaultwarden() {
  echo -ne "\n* Configuring /federated/apps/vaultwarden container.."
  spin &
  SPINPID=$!

  if [ ! -d "/federated/apps/vaultwarden" ]; then
    mkdir -p /federated/apps/vaultwarden/data/data
  fi

cat > /federated/apps/vaultwarden/docker-compose.yml <<EOF
version: '3.7'

services:
  vaultwarden:
    image: vaultwarden/server:\${IMAGE_VERSION}
    container_name: vaultwarden
    hostname: vaultwarden.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.22
    env_file:
      - ./.env
    volumes:
      - ./data/data:/data
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.vaultwarden.rule=Host(\`vaultwarden.$DOMAIN\`)"
      - "traefik.http.routers.vaultwarden.entrypoints=websecure"
      - "traefik.http.routers.vaultwarden.tls.certresolver=letsencrypt"

networks:
  federated:
    external: true
EOF

cat > /federated/apps/vaultwarden/.env <<EOF
IMAGE_VERSION="1.28.1"
DATABASE_URL=postgresql://vaultwarden:$VAULTWARDEN_SECRET@postgresql.$DOMAIN:5432/vaultwarden
WEBSOCKET_ENABLED=true
DOMAIN=https://vaultwarden.$DOMAIN
ADMIN_TOKEN=$VAULTWARDEN_SECRET
#- SIGNUPS_ALLOWED=false
SMTP_HOST=mail.$DOMAIN
SMTP_FROM=vaultwarden@$DOMAIN
SMTP_PORT=587
SMTP_SECURITY=starttls
SMTP_USERNAME=fcore
SMTP_PASSWORD=$ADMINPASS
EOF
chmod 600 /federated/apps/vaultwarden/.env
 
kill -9 $SPINPID &> /dev/null
echo -ne "done."
}
start_vaultwarden() {
  # Start service with command to make sure it's up before proceeding
  start_service "vaultwarden" "nc -z 172.99.0.22 80 &> /dev/null" "8"

  kill -9 $SPINPID &> /dev/null
  echo -ne "done."
}
