#!/bin/bash
#
# Bookstack Service

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

config_bookstack() {
  echo -ne "* Configuring bookstack container.."

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

cat > /federated/apps/bookstack/docker-compose.yml <<EOF
services:
  bookstack:
    image: lscr.io/linuxserver/bookstack:\${IMAGE_VERSION}
    container_name: bookstack
    hostname: bookstack.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.36
    extra_hosts:
      - "authelia.$DOMAIN:$EXTERNALIP"
    env_file:
      - ./.env
    volumes:
      - ./data/config:/config
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.bookstack.rule=Host(\`bookstack.$DOMAIN\`) || Host(\`documentation.$DOMAIN\`)"
      - "traefik.http.routers.bookstack.entrypoints=websecure"
      - "traefik.http.routers.bookstack.tls.certresolver=letsencrypt"

networks:
  core:
    external: true
EOF

BOOKSTACK_ADMINPASSWORD=`htpasswd -bnBC 10 "" $ADMINPASS | tr -d ':\n' | sed 's/$2y/$2b/'`
BOOKSTACK_SECRET=$(create_password);
[[ "${PLUS}" = "true" ]] && sed -i "s/letsencrypt/httpresolver/g" /federated/apps/bookstack/docker-compose.yml

cat > /federated/apps/bookstack/.env <<EOF
IMAGE_VERSION="$(current_version bookstack)"
PUID=1000
PGID=1000
APP_URL=https://bookstack.$DOMAIN
DB_HOST=pdnsmysql.$DOMAIN
DB_PORT=3306
DB_USER=bookstack
DB_PASS=$BOOKSTACK_SECRET
DB_PORT=3306
DB_DATABASE=bookstack
QUEUE_CONNECTION=database
#MAIL_DRIVER=smtp
MAIL_FROM=bookstack@$DOMAIN
MAIL_FROM_NAME=bookstack
MAIL_HOST=mail.$DOMAIN
MAIL_PORT=587
MAIL_USERNAME=$SMTPUSER
MAIL_PASSWORD=$ADMINPASS
MAIL_ENCRYPTION=TLS
EOF
chmod 600 /federated/apps/bookstack/.env

# Create database and user in mysql
docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e 'create database bookstack;'" &> /dev/null
docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e \"CREATE USER 'bookstack'@'%' IDENTIFIED BY '$BOOKSTACK_SECRET';\"" &> /dev/null
docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e \"grant all privileges on bookstack.* to 'bookstack'@'%';\"" &> /dev/null
docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e 'flush privileges;'" &> /dev/null
 
echo -ne "done.\n"
}
start_bookstack() {
  # Start service with command to make sure it's up before proceeding
  start_service "bookstack" "nc -z 192.168.0.36 80 &> /dev/null" "7"

  if [[ "${PLUS}" != "true" ]]; then
    docker exec pdns pdnsutil add-record $DOMAIN bookstack A 86400 $EXTERNALIP &> /dev/null
    docker exec pdns pdnsutil add-record $DOMAIN documentation A 86400 $EXTERNALIP &> /dev/null
  fi

  docker exec pdnsmysql mariadb -ubookstack -p$BOOKSTACK_SECRET bookstack -e "delete from users where email = 'admin@admin.com';" &> /dev/null
  docker exec bookstack php /app/www/artisan bookstack:create-admin --email="admin@$DOMAIN" --name="Admin" --password="$ADMINPASS" &> /dev/null

  # Set mail configuration
  sed -i "s#MAIL_FROM=.*#MAIL_FROM=admin@$DOMAIN#g" /federated/apps/bookstack/data/config/www/.env
  sed -i "s#MAIL_FROM_NAME=.*#MAIL_FROM_NAME=admin#g" /federated/apps/bookstack/data/config/www/.env
  sed -i "s#MAIL_HOST=.*#MAIL_HOST=mail.$DOMAIN#g" /federated/apps/bookstack/data/config/www/.env
  sed -i "s#MAIL_PORT=.*#MAIL_PORT=587#g" /federated/apps/bookstack/data/config/www/.env
  sed -i "s#MAIL_USERNAME=.*#MAIL_USERNAME=admin#g" /federated/apps/bookstack/data/config/www/.env
  sed -i "s#MAIL_PASSWORD=.*#MAIL_PASSWORD=$ADMINPASS#g" /federated/apps/bookstack/data/config/www/.env
  sed -i "s#MAIL_ENCRYPTION=.*#MAIL_ENCRYPTION=TLS#g" /federated/apps/bookstack/data/config/www/.env

  echo -ne "done.\n"
}
email_bookstack() {
  echo -ne "* Sending email to customer.."

cat > /federated/apps/mail/data/root/certs/mailfile <<EOF
<html>
<img src="https://www.federated.computer/wp-content/uploads/2023/11/logo.png" alt="" /><br>
<p>
<h4>Bookstack is now installed on $DOMAIN</h4>
<p>
Here is your applications chart on how to access this service:<br>
<p>
<h4>Applications</h4>
<style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-cul6{border-color:inherit;color:#340096;text-align:left;text-decoration:underline;vertical-align:top}
.tg .tg-acii{background-color:#FFF;border-color:inherit;color:#333;text-align:left;vertical-align:top}
.tg .tg-0hty{background-color:#000000;border-color:inherit;color:#ffffff;font-weight:bold;text-align:left;vertical-align:top}
.tg .tg-kwiq{border-color:inherit;color:#000000;text-align:left;vertical-align:top}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
</style>
<table class="tg" style="undefined;table-layout: fixed; width: 996px">
<colgroup>
<col style="width: 101.333333px">
<col style="width: 203.333333px">
<col style="width: 282.333333px">
<col style="width: 185.33333px">
<col style="width: 78.333333px">
<col style="width: 220.333333px">
</colgroup>
<thead>
  <tr>
    <th class="tg-0hty">Service</th>
    <th class="tg-0hty">Link</th>
    <th class="tg-0hty">User / Pass</th>
    <th class="tg-0hty">Access</th>
    <th class="tg-0hty">Docs</th>
    <th class="tg-0hty">Description</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-0pky">Bookstack</td>
    <td class="tg-0pky"><a href="https://bookstack.$DOMAIN/login" target="_blank" rel="noopener noreferrer"><span style="color:#340096">bookstack.$DOMAIN</span></a></td>
    <td class="tg-0pky">admin@$DOMAIN<br>$ADMINPASS</td>
    <td class="tg-0pky">User access is separate from panel</td>
    <td class="tg-cul6"><a href="https://documentation.federated.computer/docs/getting_started/welcome/" target="_blank" rel="noopener noreferrer"><span style="color:#340096">Click here</span></a></td>
    <td class="tg-0pky">Bookstack is a simple, open-source, self-hosted, easy-to-use platform (Wiki) for organising and storing information</td>
  </tr>
</tbody>
</table>
<h4>Thanks for your support!</h4>
<p>
Thank you for your support of Federated Computer. We really appreciate it and hope you have a very successful
time with Federated Core.
<p>
Again, if we can be of any assistance, please don't hesitate to get in touch.
<p>
Support: https://support.federated.computer<br>
Phone: (970) 722-8715<br>
Email: support@federated.computer<br>
<p>
It's <b>your</b> computer. Let's make it work for you!
</html>
EOF

  # Send out e-mail from mail container with details
  docker exec mail bash -c "mail -r admin@$DOMAIN -a \"Content-type: text/html\" -s \"Application installed on $DOMAIN\" $EMAIL < /root/certs/mailfile"
  rm /federated/apps/mail/data/root/certs/mailfile

  echo -ne "done.\n"
}
uninstall_bookstack() {
  echo -ne "* Uninstalling bookstack container.."

  # First stop the service
  cd /federated/apps/bookstack && docker compose -f docker-compose.yml -p bookstack down &> /dev/null

  # Delete database and user
  docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e 'drop database bookstack;'" &> /dev/null
  docker exec pdnsmysql bash -c "mariadb -uroot -p$MYSQL_ROOTPASSWORD -e 'drop user bookstack;'" &> /dev/null

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

  # Delete the image
  docker image rm lscr.io/linuxserver/bookstack:$IMAGE_VERSION &> /dev/null

  # Delete the DNS record
  if [[ "${PLUS}" != "true" ]]; then
    docker exec pdns pdnsutil delete-rrset $DOMAIN bookstack A &> /dev/null
    docker exec pdns pdnsutil delete-rrset $DOMAIN documentation A &> /dev/null
  fi

  # Uninstall the SSO configuration if it exists in authelia (authelia must exist too)
  if [[ $(grep "### Bookstack" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]]; then
    sed -i '/### Bookstack/,/### /{/### PowerDNS/!{/### /!d}}' /federated/apps/authelia/data/config/idproviders.yml
    sed -i '/### Bookstack/d' /federated/apps/authelia/data/config/idproviders.yml
    run_command "/federated/bin/stop authelia"
    run_command "/federated/bin/start authelia"
  fi

  echo -ne "done.\n"
}
configsso_bookstack() {
  if [[ "${PLUS}" != "true" ]]; then
  echo -ne "* Configuring bookstack container with SSO.."

  [ ! -d "/federated/apps/authelia" ] && failcheck "Authelia is not installed. You need this first before continuing."
  [ ! -f "/federated/apps/authelia/data/config/idproviders.yml" ] && failcheck "Authelia idproviders.yml is missing."
  [[ $(grep "### Bookstack" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]] && failcheck "Authelia already has a Bookstack configuration."

  BOOKSTACK_CLIENT_SECRET=$(create_password);
  BOOKSTACK_CLIENT_SECRET_HASH=$(docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --password $BOOKSTACK_CLIENT_SECRET | awk '{ print $2 }')

cat >> /federated/apps/authelia/data/config/idproviders.yml <<EOF
     ### Bookstack
      - client_id: 'bookstack'
        client_name: 'Bookstack'
        client_secret: $BOOKSTACK_CLIENT_SECRET_HASH
        consent_mode: 'implicit'
        public: false
        authorization_policy: 'one_factor'
        redirect_uris:
          - 'https://bookstack.$DOMAIN/oidc/callback'
        scopes:
          - 'openid'
          - 'profile'
          - 'email'
        userinfo_signed_response_alg: 'none'
EOF

  # Restart Authelia for changes to take the above configuration
  run_command "/federated/bin/stop authelia"
  run_command "/federated/bin/start authelia"

cat >> /federated/apps/bookstack/.env <<EOF
AUTH_METHOD=oidc
AUTH_AUTO_INITIATE=false
OIDC_NAME=Authelia
OIDC_DISPLAY_NAME_CLAIMS=name
OIDC_CLIENT_ID=bookstack
OIDC_CLIENT_SECRET=$BOOKSTACK_CLIENT_SECRET
OIDC_ISSUER=https://authelia.$DOMAIN
OIDC_ISSUER_DISCOVER=true
OIDC_EXTERNAL_ID_CLAIM=email
OIDC_END_SESSION_ENDPOINT=https://authelia.$DOMAIN/logout?rd=https://dashboard.$DOMAIN
#APP_DEBUG=true
#OIDC_DUMP_USER_DETAILS=true
EOF

  # Add in extra hosts config
  add_authelia_config_to_dockercompose "bookstack"

  # Setup external_auth_id for each user in bookstack users table
  BOOKSTACK_SECRET=$(cat /federated/apps/bookstack/.env | grep "DB_PASS" | awk -F= '{ print $2 }')
  for i in $(docker exec pdnsmysql mariadb -ubookstack -p${BOOKSTACK_SECRET} bookstack -sN -e "select email from users;"); do
    docker exec pdnsmysql mariadb -ubookstack -p${BOOKSTACK_SECRET} bookstack -e "update users set external_auth_id = '$i' where email = '$i'";
  done

  run_command "/federated/bin/stop bookstack"
  run_command "/federated/bin/start bookstack"

  echo -ne "done.\n"
  fi
}
configsso_bookstack_plus() {
  BOOKSTACK_CLIENT_SECRET=$(cat /federated/apps/bookstack/.bookstack.client.secret)

cat >> /federated/apps/bookstack/.env <<EOF
AUTH_METHOD=oidc
AUTH_AUTO_INITIATE=false
OIDC_NAME=Authelia
OIDC_DISPLAY_NAME_CLAIMS=name
OIDC_CLIENT_ID=bookstack
OIDC_CLIENT_SECRET=$BOOKSTACK_CLIENT_SECRET
OIDC_ISSUER=https://authelia.$DOMAIN
OIDC_ISSUER_DISCOVER=true
OIDC_EXTERNAL_ID_CLAIM=email
OIDC_END_SESSION_ENDPOINT=https://authelia.$DOMAIN/logout?rd=https://dashboard.$DOMAIN
#APP_DEBUG=true
#OIDC_DUMP_USER_DETAILS=true
EOF

  # Setup external_auth_id for each user in bookstack users table
  BOOKSTACK_SECRET=$(cat /federated/apps/bookstack/.env | grep "DB_PASS" | awk -F= '{ print $2 }')
  for i in $(docker exec pdnsmysql mariadb -ubookstack -p${BOOKSTACK_SECRET} bookstack -sN -e "select email from users;"); do
    docker exec pdnsmysql mariadb -ubookstack -p${BOOKSTACK_SECRET} bookstack -e "update users set external_auth_id = '$i' where email = '$i'";
  done

  run_command "/federated/bin/stop bookstack"
  run_command "/federated/bin/start bookstack"
}
