#!/bin/bash
#
# Vaultwarden Service

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

config_vaultwarden() {
  echo -ne "\n* Configuring /federated/apps/vaultwarden container.."

  if [ ! -d "/federated/apps/vaultwarden" ]; then
    mkdir -p /federated/apps/vaultwarden/data/data
  fi
  VAULTWARDEN_SECRET=$(create_password)

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
SIGNUPS_ALLOWED=false
SIGNUPS_DOMAINS_WHITELIST=$DOMAIN
SIGNUPS_VERIFY=true
EOF
chmod 600 /federated/apps/vaultwarden/.env

# Create database and user in postgresql
docker exec postgresql psql -U postgres -c "CREATE DATABASE vaultwarden" &> /dev/null
docker exec postgresql psql -U postgres -c "CREATE USER vaultwarden WITH PASSWORD '$VAULTWARDEN_SECRET'" &> /dev/null
docker exec postgresql psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE vaultwarden TO vaultwarden" &> /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"

  docker exec pdns pdnsutil add-record $DOMAIN vaultwarden A 86400 $EXTERNALIP &> /dev/null
  [ $? -ne 0 ] && fail "Couldn't add dns record"

  echo -ne "done."
}
