#!/bin/bash

#set -o xtrace

if [[ ! -f docker-compose.yml ]]; then
  printf "Needs to be run from compose directory\n"
  exit 1
fi

source .env

P1="sudo docker compose exec -u 1000"
P2="cd /config/www/nextcloud; php occ"

RE=$($P1 nextc bash -c "$P2 status" |grep "installed: false")
if [[ $? -eq 0 && -n $RE ]]; then
  read -p "Enter Admin name: " USERNAME
  if [[ -z $USERNAME ]]; then printf "Nothing in username\n"; exit; fi
  if [[ -d $DATA/ncdata/$USERNAME ]]; then printf "Files exist for user $USERNAME\n"; exit 1; fi  
  ROOTPASS="$(LC_ALL=C </dev/urandom tr -dc A-Za-z0-9 | head -c 10)"
  USERPASS="$(LC_ALL=C </dev/urandom tr -dc A-Za-z0-9 | head -c 4)"
  printf "Admin Name: $USERNAME\n"
  printf "Admin Pass: $USERPASS\n"
  printf "Database Password: $ROOTPASS\n"
  printf "\n"
  read -r -s -N 1 -p "Press 'Enter' to continue " ENTER
  if [[ $ENTER != $'\n' ]]; then exit; fi
  printf "\n"
  printf "Installing Nextcloud...\n"

  RE=$($P1 nextc-db bash -c "mysqladmin -u root password $ROOTPASS")
  if [[ $? -eq 0 ]]; then
    printf "Root password changed\n"
    printf "ROOTPASS: $ROOTPASS\n" > install.log

    RE=$($P1 nextc bash -c "$P2 maintenance:install --database mysql \
    --database-host nextc-db --database-name ncdb --database-user root \
    --database-pass $ROOTPASS --admin-user $USERNAME --admin-pass $USERPASS --data-dir /ncdata")
    if [[ $? -eq 0 ]]; then
      printf "USERNAME: $USERNAME\nUSERPASS: $USERPASS\n" >> install.log
      printf "Install success\n"
    else
      exit 1;
    fi
  else
    exit 1;
  fi
fi

read -p "Enter Trusted domain: " DOMAIN

RE=$($P1 nextc bash -c "$P2 config:system:set trusted_domains 2 --value=$DOMAIN")
if [[ $? -eq 0 ]]; then
  printf "Trusted Domain $DOMAIN set\n"
else
  exit 1;
fi

set +o xtrace

