Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
freedombone-app-pleroma 71.68 KiB
#!/bin/bash
#  _____               _           _
# |   __|___ ___ ___ _| |___ _____| |_ ___ ___ ___
# |   __|  _| -_| -_| . | . |     | . | . |   | -_|
# |__|  |_| |___|___|___|___|_|_|_|___|___|_|_|___|
#
#                              Freedom in the Cloud
#
# Pleroma backend application
#
# License
# =======
#
# Copyright (C) 2017-2019 Bob Mottram <bob@freedombone.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

VARIANTS='full full-vim social'

APP_CATEGORY=social

IN_DEFAULT_INSTALL=0
SHOW_ON_ABOUT=1
REQUIRES_APP=

PLEROMA_DOMAIN_NAME=
PLEROMA_CODE=
PLEROMA_PORT=4000
PLEROMA_ONION_PORT=8011
PLEROMA_REPO="https://git.pleroma.social/pleroma/pleroma.git"
PLEROMA_COMMIT='98d9dcd509ab6823e38b3ddbce1f5fc4f3d5a82c'
PLEROMA_ADMIN_PASSWORD=
PLEROMA_DIR=/etc/pleroma
PLEROMA_SECRET_KEY=""
pleroma_secret=$PLEROMA_DIR/config/dev.secret.exs

PLEROMA_BACKGROUND_IMAGE_URL=

PLEROMA_TITLE='Pleroma Server'

# Number of months after which posts expire
PLEROMA_EXPIRE_MONTHS=3
pleroma_expire_posts_script=/usr/bin/pleroma-expire-posts
blocking_script_file=/usr/bin/pleroma-blocking

emoji_resolution='128x128'

# limit hellthreads with zillions of mentions
maximum_tagged_thread_participants=7

# whether the install function is running
pleroma_installing=

PLEROMA_SHORT_DESCRIPTION=$'Federated microblogging'
PLEROMA_DESCRIPTION=$'Federated microblogging'
PLEROMA_MOBILE_APP_URL='https://f-droid.org/packages/com.keylesspalace.tusky'

pleroma_variables=(ONION_ONLY
                   PLEROMA_DOMAIN_NAME
                   PLEROMA_CODE
                   PLEROMA_WELCOME_MESSAGE
                   PLEROMA_BACKGROUND_IMAGE_URL
                   DDNS_PROVIDER
                   PLEROMA_TITLE
                   PLEROMA_EXPIRE_MONTHS
                   MY_EMAIL_ADDRESS
                   MY_USERNAME)

function pleroma_enable_web_push_encryption {
    if grep -q 'web_push_encryption' "$pleroma_secret"; then
        return
    fi

    cd $PLEROMA_DIR || return
    sudo -u pleroma mix web_push.gen.keypair | sudo tee -a "$pleroma_secret"
    sed -i "s|administrator@example.com|$MY_EMAIL_ADDRESS|g" "$pleroma_secret"
    sed -i '/# Put the following/d' "$pleroma_secret"
    if [ $pleroma_installing ]; then
        increment_app_install_progress
    fi
    sudo -u postgres psql pleroma -c "create extension if not exists pg_trgm"
    if [ $pleroma_installing ]; then
        increment_app_install_progress
    fi
    sudo -u postgres psql pleroma -c 'create extension if not exists "uuid-ossp"'
    if [ $pleroma_installing ]; then
        increment_app_install_progress
    fi
    sudo -u pleroma mix ecto.migrate --force
    if [ $pleroma_installing ]; then
        increment_app_install_progress
    fi
    pleroma_recompile
    if [ $pleroma_installing ]; then
        increment_app_install_progress
    fi

    PLEROMA_PUSH_PUBLIC_KEY=$(grep "public_key:" "$pleroma_secret" | head -n 1 | awk -F '"' '{print $2}')
    PLEROMA_PUSH_PRIVATE_KEY=$(grep "private_key:" "$pleroma_secret" | head -n 1 | awk -F '"' '{print $2}')
    if [ "$PLEROMA_PUSH_PUBLIC_KEY" ]; then
        write_config_param PLEROMA_PUSH_PUBLIC_KEY "$PLEROMA_PUSH_PUBLIC_KEY"
    else
        echo $'web_push_encryption failed: no public key'
        return
    fi

    if [ "$PLEROMA_PUSH_PRIVATE_KEY" ]; then
        write_config_param PLEROMA_PUSH_PRIVATE_KEY "$PLEROMA_PUSH_PRIVATE_KEY"
    else
        echo $'web_push_encryption failed: no private key'
        return
    fi
}

function pleroma_set_permissions {
    # set permissions on directories
    if [ -d "$PLEROMA_DIR/config" ]; then
        chmod 644 "$PLEROMA_DIR/config"/*
    fi
    if [ -d "$PLEROMA_DIR/deps" ]; then
        chmod -R 755 "$PLEROMA_DIR/deps"
    fi
}

function pleroma_create_recompile_command {
    { echo '#!/bin/bash';
      echo "cd $PLEROMA_DIR || exit 1";
      echo "chown -R pleroma:pleroma $PLEROMA_DIR";
      echo 'sudo -u pleroma mix clean';
      echo 'sudo -u pleroma mix deps.compile';
      echo 'sudo -u pleroma mix compile';
      echo "chmod 644 $PLEROMA_DIR/config/*";
      echo "chmod -R 755 $PLEROMA_DIR/deps/*";
      echo 'systemctl restart pleroma'; } > /usr/bin/pleroma-recompile
    chmod +x /usr/bin/pleroma-recompile
}

function pleroma_recompile {
    # necessary after parameter changes

    if [ ! -f /usr/bin/pleroma-recompile ]; then
        pleroma_create_recompile_command
    fi

    if ! grep -q 'chmod' /usr/bin/pleroma-recompile; then
        pleroma_create_recompile_command
    fi

    /usr/bin/pleroma-recompile
}

function pleroma_setting_background {
    pleroma_new_background="$1"

    if [ "$pleroma_new_background" ]; then
        url="$pleroma_new_background"

        ext=
        if [ ${#url} -gt 0 ]; then
            if [[ "$url" == *".jpeg" || "$url" == *".jpg" ]]; then
                ext="jpg"
            fi
            if [[ "$url" == *".png" ]]; then
                ext="png"
            fi
            if [[ "$url" == *".gif" ]]; then
                ext="gif"
            fi
        fi

        if [ ${#ext} -gt 0 ]; then
            cd "$PLEROMA_DIR" || return

            # remove any existing image
            if [ -f "bg_custom.${ext}" ]; then
                rm "bg_custom.${ext}"
            fi

            # get the new image
            wget "$url" -O "bg_custom.${ext}"
            if [ ! -f "bg_custom.${ext}" ]; then
                echo "$url"
                echo $'Custom background image for pleroma could not be downloaded'
                return
            fi

            if [ -d priv/static/static ]; then
                cp "bg_custom.${ext}" "priv/static/static/bg_custom.${ext}"
                sed -i "s|\"background\":.*|\"background\": \"/static/bg_custom.${ext}\",|g" priv/static/static/config.json
                if [ -f "$pleroma_secret" ]; then
                    if grep -q "\"background\":" "$pleroma_secret"; then
                        sed -i "s|\"background\":.*|\"background\": \"/static/bg_custom.${ext}\",|g" "$pleroma_secret"
                    fi
                fi
                chown pleroma:pleroma "priv/static/static/bg_custom.${ext}"
            fi

            rm "bg_custom.${ext}"
            pleroma_recompile
        fi
    fi
}

function pleroma_setting_emoji {
    shortcode="$1"
    image_url="$2"
    if [ ! "$shortcode" ]; then
        return
    fi
    if [[ "$shortcode" == *' '* || "$shortcode" == *':'* ]]; then
        return
    fi
    if [ ${#shortcode} -gt 32 ]; then
        return
    fi
    if [[ "$image_url" != 'http'* ]]; then
        return
    fi
    if [ ${#image_url} -gt 256 ]; then
        return
    fi

    image_extension=
    if [[ "$image_url" == *'.jpg' || "$image_url" == *'.jpeg' ]]; then
        image_extension='jpg'
    fi
    if [[ "$image_url" == *'.gif' ]]; then
        image_extension='gif'
    fi
    if [[ "$image_url" == *'.png' ]]; then
        image_extension='png'
    fi
    if [ ! $image_extension ]; then
        echo $'Invalid image type'
        return
    fi

    if [ ! -d $PLEROMA_DIR/priv/static/emoji ]; then
        mkdir -p $PLEROMA_DIR/priv/static/emoji
    fi

    image_filename=$PLEROMA_DIR/priv/static/emoji/${shortcode}.${image_extension}
    if [ -f "$image_filename" ]; then
        mv "$image_filename" "${image_filename}.prev"
    fi
    wget "$image_url" -O "$image_filename"
    if [ ! -f "$image_filename" ]; then
        if [ -f "${image_filename}.prev" ]; then
            mv "${image_filename}.prev" "${image_filename}"
        fi
        return
    fi
    rm "${image_filename}.prev"

    if [[ "$image_url" == *'.jpg' || "$image_url" == *'.jpeg' || "$image_url" == *'.gif' ]]; then
        convert "$image_filename" -resize "$emoji_resolution" "$PLEROMA_DIR/priv/static/emoji/${shortcode}.png"
        if [ ! -f "$PLEROMA_DIR/priv/static/emoji/${shortcode}.png" ]; then
            return
        fi

        # remove the original
        rm "$image_filename"

        image_extension='png'
        image_filename=$PLEROMA_DIR/priv/static/emoji/${shortcode}.${image_extension}
    else
        convert "$image_filename" -resize "$emoji_resolution" "$image_filename"
    fi

    if ! grep -q "${shortcode}," $PLEROMA_DIR/config/emoji.txt; then
        echo "${shortcode}, /emoji/${shortcode}.${image_extension}" >> $PLEROMA_DIR/config/emoji.txt
    else
        sed -i "s|${shortcode},.*|${shortcode}, /emoji/${shortcode}.${image_extension}|g" $PLEROMA_DIR/config/emoji.txt
    fi

    chown -R pleroma:pleroma $PLEROMA_DIR
    cd $PLEROMA_DIR || exit 26
    pleroma_recompile
}

function pleroma_setting_registration {
    allow_registration="$1"


    if [[ "$allow_registration" == '1' ]]; then
        if ! grep -q 'registrations_open' $pleroma_secret; then
            sed -i '/config :pleroma, :instance/a registrations_open: true,' $pleroma_secret
            sed -i 's|registrations_open:|  registrations_open:|g' $pleroma_secret
        fi
        sed -i 's|registrations_open: false|registrations_open: true|g' $PLEROMA_DIR/config/config.exs
        sed -i 's|registrations_open: False|registrations_open: true|g' $PLEROMA_DIR/config/config.exs
        sed -i 's|registrations_open: false|registrations_open: true|g' $pleroma_secret
        sed -i 's|registrations_open: False|registrations_open: true|g' $pleroma_secret
        sed -i 's|"registrationOpen": false|"registrationOpen": true|g' $PLEROMA_DIR/priv/static/static/config.json
        sed -i 's|"registrationOpen": False|"registrationOpen": true|g' $PLEROMA_DIR/priv/static/static/config.json
        cd $PLEROMA_DIR || exit 56
        pleroma_recompile
    fi

    if [[ "$allow_registration" == '0' ]]; then
        if ! grep -q 'registrations_open' $pleroma_secret; then
            sed -i '/config :pleroma, :instance/a registrations_open: false,' $pleroma_secret
            sed -i 's|registrations_open:|  registrations_open:|g' $pleroma_secret
        fi
        sed -i 's|registrations_open: true|registrations_open: false|g' $PLEROMA_DIR/config/config.exs
        sed -i 's|registrations_open: True|registrations_open: false|g' $PLEROMA_DIR/config/config.exs
        sed -i 's|registrations_open: true|registrations_open: false|g' $pleroma_secret
        sed -i 's|registrations_open: True|registrations_open: false|g' $pleroma_secret
        sed -i 's|"registrationOpen": true|"registrationOpen": false|g' $PLEROMA_DIR/priv/static/static/config.json
        sed -i 's|"registrationOpen": True|"registrationOpen": false|g' $PLEROMA_DIR/priv/static/static/config.json
        cd $PLEROMA_DIR || exit 45
        pleroma_recompile
    fi
}

function pleroma_enable_chat {
    if [[ "$1" == 't'* || "$1" == 'y'* || "$1" == 'T'* || "$1" == 'Y'* ]]; then
        sed -i 's|"chatDisabled":.*|"chatDisabled": false,|g' $PLEROMA_DIR/priv/static/static/config.json
        sed -i 's|:chat, enabled:.*|:chat, enabled: true|g' $PLEROMA_DIR/config/config.exs
    else
        sed -i 's|"chatDisabled":.*|"chatDisabled": true,|g' $PLEROMA_DIR/priv/static/static/config.json
        sed -i 's|:chat, enabled:.*|:chat, enabled: false|g' $PLEROMA_DIR/config/config.exs
    fi
    pleroma_recompile
}

function create_pleroma_blocklist {
    { echo '#!/bin/bash';
      echo '';
      echo 'websub_server_subscriptions_query="DELETE FROM websub_server_subscriptions WHERE"';
      echo 'websub_server_subscriptions_updated='
      echo '';
      echo "if [ ! -f /root/${PROJECT_NAME}-firewall-domains.cfg ]; then";
      echo '    exit 0';
      echo 'fi';
      echo '';
      echo 'if [ -f /tmp/pleroma-blocking.lock ]; then';
      echo '    cd /tmp';
      echo '    find ./pleroma*.lock -type f -mmin +5 -exec rm {} \;';
      echo '    if [ -f /tmp/pleroma-blocking.lock ]; then';
      echo '        exit 0';
      echo '    fi';
      echo 'fi';
      echo '';
      echo 'touch /tmp/pleroma-blocking.lock';
      echo 'filter_str=';
      echo '';
      echo 'while read blocked; do';
      echo "    if [[ \"\$blocked\" == *\".\"* && \"\$blocked\" != *\"@\"* ]]; then";
      echo "        if [ \${#blocked} -gt 4 ]; then";
      echo '            # Create a filter string for the pleroma configuration';
      echo "            if [ \"\$filter_str\" ]; then";
      echo "                filter_str=\"\${filter_str}, \\\"\$blocked\\\"\"";
      echo '            else';
      echo "                filter_str=\"\\\"\${blocked}\\\"\"";
      echo '            fi';
      echo '';
      echo "            if ! grep -q \"127.0.0.1  \$blocked\" /etc/hosts; then";
      echo "                echo \"127.0.0.1  \$blocked\" >> /etc/hosts";
      echo '            fi';
      echo '';
      echo "            if [ \$websub_server_subscriptions_updated ]; then";
      echo "                websub_server_subscriptions_query=\"\${websub_server_subscriptions_query} or\"";
      echo '            fi';
      echo "            websub_server_subscriptions_query=\"\${websub_server_subscriptions_query} callback like '%\${blocked}%'\"";
      echo '        fi';
      echo '    fi';
      echo 'done </root/freedombone-firewall-domains.cfg';
      echo '';
      echo 'while read blocked; do';
      echo "    if [[ \"\$blocked\" == *\".\"* && \"\$blocked\" == *\"@\"* ]]; then";
      echo "        if [ \${#blocked} -gt 4 ]; then";

      echo "            curr_user_query=\"SELECT nickname FROM users where nickname ilike '%\${blocked}%'\"";
      echo "            curr_user_present=\$(sudo -u postgres psql -d pleroma -c \"\$curr_user_query\")";
      echo "            if [[ \"\$curr_user_present\" != *'(0 '* ]]; then";
      echo "                /bin/bash -c \"cd /etc/pleroma;sudo -u pleroma mix deactivate_user \${blocked}\" &";
      echo '                sleep 1';
      echo '            fi';
      echo '        fi';
      echo '    fi';
      echo 'done </root/freedombone-firewall-domains.cfg';
      echo '';
      echo "if [ \"\$filter_str\" ]; then";
      echo "    if ! grep -q \" \$filter_str \" $pleroma_secret; then";
      echo '        systemctl stop pleroma';
      echo "        sed -i \"s| media_removal:.*| media_removal: [ \$filter_str ],|g\" $pleroma_secret";
      echo "        sed -i \"s| federated_timeline_removal:.*| federated_timeline_removal: [ \$filter_str ],|g\" $pleroma_secret";
      echo "        sed -i \"s| reject:.*| reject: [ \$filter_str ]|g\" $pleroma_secret";
      echo "        sed -i \"s| quarantined_instances:.*| quarantined_instances: [ \$filter_str ],|g\" $pleroma_secret";
      echo "        cd $PLEROMA_DIR";
      echo "        chown -R pleroma:pleroma $PLEROMA_DIR";
      echo '        sudo -u pleroma mix clean';
      echo '        sudo -u pleroma mix deps.compile';
      echo '        sudo -u pleroma mix compile';
      echo '        systemctl restart pleroma';
      echo '    fi';
      echo 'fi';
      echo '';
      echo "if [ \$websub_server_subscriptions_updated ]; then";
      echo '    cd /etc/postgresql';
      echo "    sudo -u postgres psql -d pleroma -c \"\$websub_server_subscriptions_query\"";
      echo 'fi';
      echo '';
      echo 'rm /tmp/pleroma-blocking.lock'; } > $blocking_script_file

    chmod +x $blocking_script_file

    if ! grep -q "$blocking_script_file" /etc/crontab; then
        cron_add_mins 1 "$blocking_script_file 2> /dev/null"
    fi
}

function expire_pleroma_posts {
    domain_name=$1
    expire_months=$3

    if [ ! "$expire_months" ]; then
        expire_months=3
    fi

    #expire_days=$((expire_months * 30))

    # files are what take up most of the backup time, so don't keep them for very long
    expire_days_files=7

    # To prevent the database size from growing endlessly this script expires posts
    # after a number of months
    if [ ! -d $PLEROMA_DIR ]; then
        return
    fi

    { echo '#!/bin/bash';
      echo "plmonths=\"$PLEROMA_EXPIRE_MONTHS\"";
      echo "if [ \${#plmonths} -eq 0 ]; then";
      echo '    exit 1';
      echo 'fi';
      echo "if [[ \"\$plmonths\" == \"0\" ]]; then";
      echo '    exit 2';
      echo 'fi';
      echo "oldate=\$(date +%Y-%m-%d --date=\"\$plmonths months ago\")";
      echo 'cd /etc/postgresql';
      echo "sudo -u postgres psql -d pleroma -c \"DELETE FROM notifications WHERE inserted_at <= '\$oldate 01:01:01'\"";
      echo "sudo -u postgres psql -d pleroma -c \"DELETE FROM objects WHERE inserted_at <= '\$oldate 01:01:01'\""; } > $pleroma_expire_posts_script
    chmod +x $pleroma_expire_posts_script

    pleroma_expire_script=/etc/cron.daily/pleroma-expire
    expire_days_files_threshold=$((expire_days_files - 1))
    { echo '#!/bin/bash';
      echo 'cd /etc/postgresql';
      echo "if [ -d $PLEROMA_DIR/tempfiles ]; then";
      echo "    rm -rf $PLEROMA_DIR/tempfiles";
      echo 'fi';
      echo '';
      echo '# make directory to temporarily store local avatars';
      echo "mkdir $PLEROMA_DIR/tempfiles";
      echo '';
      echo '# get the local avatar files';
      echo "avatars=\$(sudo -u postgres psql -d pleroma -c \"select avatar->>'url' from users where avatar->>'url' like '%${domain_name}%'\")";
      echo '';
      echo '# copy the avatar files to a temporary directory';
      echo "arr=( \$avatars )";
      echo "for i in \${arr[@]}; do";
      echo "    if [[ \"\$i\" == *'/media/'* ]]; then";
      echo "        imagefile=$PLEROMA_DIR/uploads/\$(echo \$i | sed 's|\"||g' | sed 's|,||g' | awk -F '/media/' '{print \$2}');";
      echo "        if [ -f \$imagefile ]; then";
      echo "            imagedir=$PLEROMA_DIR/uploads/\$(echo \$imagefile | awk -F '/' '{print \$5}')";
      echo "            nowdate=\$(date +%s)";
      echo "            sinceepoch=\$(date +%s -r \$imagefile)";
      echo "            daysold=\$(((\$nowdate - \$sinceepoch) / 86400))";
      echo "            if [ \$daysold -ge ${expire_days_files_threshold} ]; then";
      echo "                cp -rp \$imagedir $PLEROMA_DIR/tempfiles";
      echo '            fi';
      echo '        fi';
      echo '    fi';
      echo 'done';
      echo '';
      echo '# get the local banner files';
      echo "banners=\$(sudo -u postgres psql -d pleroma -c \"select avatar->>'banner' from users where avatar->>'url' like '%${domain_name}%'\")";
      echo '';
      echo '# copy the banner files to a temporary directory';
      echo "arr=( \$banners )";
      echo "for i in \${arr[@]}; do";
      echo "    if [[ \"\$i\" == *'/media/'* ]]; then";
      echo "        imagefile=$PLEROMA_DIR/uploads/\$(echo \$i | sed 's|\"||g' | sed 's|,||g' | awk -F '/media/' '{print \$2}');";
      echo "        if [ -f \$imagefile ]; then";
      echo "            imagedir=$PLEROMA_DIR/uploads/\$(echo \$imagefile | awk -F '/' '{print \$5}')";
      echo "            nowdate=\$(date +%s)";
      echo "            sinceepoch=\$(date +%s -r \$imagefile)";
      echo "            daysold=\$(((\$nowdate - \$sinceepoch) / 86400))";
      echo "            if [ \$daysold -ge ${expire_days_files_threshold} ]; then";
      echo "                cp -rp \$imagedir $PLEROMA_DIR/tempfiles";
      echo '            fi';
      echo '        fi';
      echo '    fi';
      echo 'done';
      echo '';
      echo '# delete old files';
      echo "find $PLEROMA_DIR/uploads/* -mtime +${expire_days_files} -exec rm -rf {} +";
      echo '';
      echo '# move avatar files back to uploads';
      echo "chown -R pleroma:pleroma $PLEROMA_DIR/tempfiles";
      echo "mv $PLEROMA_DIR/tempfiles/* $PLEROMA_DIR/uploads";
      echo "rm -rf $PLEROMA_DIR/tempfiles";
      echo '';
      echo "$pleroma_expire_posts_script 2> /dev/null"; } > $pleroma_expire_script
    chmod +x $pleroma_expire_script

    # remove any old cron job
    if grep -q "pleroma-expire" /etc/crontab; then
        sed -i "/pleroma-expire/d" /etc/crontab
        rm /usr/bin/pleroma-expire
    fi

    # remove old expire script
    if [ -f /etc/cron.weekly/clear-pleroma-database ]; then
        rm /etc/cron.weekly/clear-pleroma-database
    fi
}

function logging_on_pleroma {
    echo -n ''
}

function logging_off_pleroma {
    echo -n ''
}

function remove_user_pleroma {
    remove_username="$1"

    if [ ! "$remove_username" ]; then
        return
    fi

    cd $PLEROMA_DIR || exit 25
    sudo -u pleroma mix pleroma.user rm "$remove_username"

    cd /etc/postgresql || exit 26
    sudo -u postgres psql -d pleroma -c "delete from users where nickname is null and local is true;"
    sudo -u postgres psql -d pleroma -c "delete from users where nickname = '$remove_username' and local is true;"

    "${PROJECT_NAME}-pass" -u "$remove_username" --rmapp pleroma
}

function add_user_pleroma {
    new_username="$1"
    new_user_password="$2"

    cd $PLEROMA_DIR || exit 34
    echo 'y' | sudo -u pleroma mix pleroma.user new "$new_username" "$new_username@$HOSTNAME" --bio $"Your bio goes here" --password "$new_user_password"
    "${PROJECT_NAME}-pass" -u "$new_username" -a pleroma -p "$new_user_password"
    echo '0'
}

function install_interactive_pleroma {
    if [ ! "$ONION_ONLY" ]; then
        ONION_ONLY='no'
    fi

    if [[ $ONION_ONLY != "no" ]]; then
        PLEROMA_DOMAIN_NAME='pleroma.local'
    else
        PLEROMA_DETAILS_COMPLETE=
        while [ ! $PLEROMA_DETAILS_COMPLETE ]
        do
            data=$(mktemp 2>/dev/null)
            dialog --backtitle $"Freedombone Configuration" \
                   --title $"Pleroma Configuration" \
                   --form $"\\nPlease enter your Pleroma details. The background image URL can be left blank.\\n\\nIMPORTANT: This should be a domain name which is supported by Let's Encrypt:" 16 65 4 \
                   $"Domain:" 1 1 "$(grep 'PLEROMA_DOMAIN_NAME' temp.cfg | awk -F '=' '{print $2}')" 1 25 33 40 \
                   $"Title:" 2 1 "$(grep "$PLEROMA_TITLE" temp.cfg | awk -F '=' '{print $2}')" 2 25 255 255 \
                   $"Background image URL:" 3 1 "$(grep "$PLEROMA_BACKGROUND_IMAGE_URL" temp.cfg | awk -F '=' '{print $2}')" 3 25 255 255 \
                   2> "$data"
            sel=$?
            case $sel in
                1) rm -f "$data"
                   exit 1;;
                255) rm -f "$data"
                     exit 1;;
            esac
            PLEROMA_DOMAIN_NAME=$(sed -n 1p < "$data")
            title=$(sed -n 2p < "$data")
            if [ ${#title} -gt 1 ]; then
                PLEROMA_TITLE="$title"
            fi
            img_url=$(sed -n 3p < "$data")
            if [ ${#img_url} -gt 1 ]; then
                PLEROMA_BACKGROUND_IMAGE_URL=$img_url
            fi
            if [ "$PLEROMA_DOMAIN_NAME" ]; then
                if [[ $PLEROMA_DOMAIN_NAME == "$HUBZILLA_DOMAIN_NAME" ]]; then
                    PLEROMA_DOMAIN_NAME=""
                fi
                TEST_DOMAIN_NAME=$PLEROMA_DOMAIN_NAME
                validate_domain_name
                if [[ "$TEST_DOMAIN_NAME" != "$PLEROMA_DOMAIN_NAME" ]]; then
                    PLEROMA_DOMAIN_NAME=
                    dialog --title $"Domain name validation" --msgbox "$TEST_DOMAIN_NAME" 15 50
                fi
            fi
            if [ $PLEROMA_DOMAIN_NAME ]; then
                PLEROMA_DETAILS_COMPLETE="yes"
            fi
            rm -f "$data"
        done

        # remove any invalid characters
        if [ ${#PLEROMA_TITLE} -gt 0 ]; then
            new_title=${PLEROMA_TITLE//\'/}
            PLEROMA_TITLE="$new_title"
        fi

        # save the results in the config file
        write_config_param "PLEROMA_TITLE" "$PLEROMA_TITLE"
        write_config_param "PLEROMA_BACKGROUND_IMAGE_URL" "$PLEROMA_BACKGROUND_IMAGE_URL"
    fi
    write_config_param "PLEROMA_DOMAIN_NAME" "$PLEROMA_DOMAIN_NAME"
    APP_INSTALLED=1
}

function change_password_pleroma {
#    curr_username="$1"
    new_user_password="$2"

    #${PROJECT_NAME}-pass -u "$curr_username" -a pleroma -p "$new_user_password"
}

function pleroma_create_database_failed {
    run_system_query_postgresql "ALTER USER pleroma NOSUPERUSER;"
    run_system_query_postgresql "ALTER USER pleroma NOCREATEDB;"
}

function pleroma_create_config {
    config_filename="$1"
    domain=$PLEROMA_DOMAIN_NAME
    domain_scheme='https'
    domain_port=443

    pleroma_http_security='true'
    if [[ "$ONION_ONLY" != 'no' ]]; then
        domain=$PLEROMA_ONION_HOSTNAME
        domain_scheme='http'
        domain_port=80
        pleroma_http_security='false'
    fi

    pleroma_background_image='aurora_borealis.jpg'

    { echo 'use Mix.Config';
      echo '';
      echo 'config :pleroma, Pleroma.Web.Endpoint,';
      echo '  pubsub: [name: Pleroma.Web.PubSub, adapter: Phoenix.PubSub.PG2],';
      echo "  secret_key_base: \"$PLEROMA_SECRET_KEY\",";
      echo "  signing_salt: \"$PLEROMA_SIGNING_SALT\",";
      echo "  secure_cookie_flag: true,";
      echo "  http: [port: $PLEROMA_PORT],";
      echo '  protocol: "http",';
      echo '  debug_errors: true,';
      echo '  code_reloader: true,';
      echo '  check_origin: true,';
      echo '  watchers: [],';
      echo "  url: [host: \"$domain\", scheme: \"$domain_scheme\", port: $domain_port]";
      echo '';
      echo "config :pleroma, :http, proxy_url: {:socks5, :localhost, 9050}";
      echo '';
      # shellcheck disable=SC2028
      echo "config :logger, :console, format: \"[\$level] \$message\\n\", level: :warn";
      echo '';
      echo 'config :comeonin, :pbkdf2_rounds, 1';
      echo '';
      echo 'config :pleroma, Pleroma.Upload,';
      echo '  uploads: "uploads",';
      echo '  strip_exif: true';
      echo '';
      echo '# begin filtering';
      echo 'config :pleroma, :instance,';
      echo '  registrations_open: false,';
      echo '  federating: true,';
      echo '  limit: 5000,';
      echo '  public: true,';
      echo '  allow_relay: false,';
      echo '  finmoji_enabled: true,';
      echo '  quarantined_instances: [],';
      echo '  mrf_transparency: false,';
      echo '  allowed_post_formats: [';
      echo '    "text/plain",';
      echo '    "text/html",';
      echo '    "text/markdown"';
      echo '  ],';
      echo '  rewrite_policy: Pleroma.Web.ActivityPub.MRF.SimplePolicy';
      echo '';
      echo 'config :pleroma, :mrf_simple,';
      echo '  media_removal: [],';
      echo '  media_nsfw: [],';
      echo '  federated_timeline_removal: [],';
      echo '  accept: [],';
      echo '  reject: []';
      echo '';
      echo 'config :phoenix, :stacktrace_depth, 20';
      echo '';
      echo 'config :pleroma, :markup,';
      echo '  allow_inline_images: true,';
      echo '  allow_headings: true,';
      echo '  allow_tables: true,';
      echo '  allow_fonts: false,';
      echo '  scrub_policy: [';
      echo '    Pleroma.HTML.Transform.MediaProxy,';
      echo '    Pleroma.HTML.Scrubber.Default';
      echo '  ]';
      echo '';
      echo 'config :pleroma, Pleroma.Repo,';
      echo '  adapter: Ecto.Adapters.Postgres,';
      echo '  username: "pleroma",';
      echo "  password: \"$PLEROMA_ADMIN_PASSWORD\",";
      echo '  database: "pleroma",';
      echo '  hostname: "localhost",';
      echo '  pool_size: 10';
      echo '';
      echo 'config :pleroma, :mrf_rejectnonpublic,';
      echo '  allow_followersonly: true,';
      echo '  allow_direct: true';
      echo '';
      echo "config :pleroma, :mrf_hellthread, threshold: $maximum_tagged_thread_participants";
      echo '';
      echo 'config :pleroma, :fe,';
      echo '  theme: "mammal",';
      echo '  logo: "/static/logo.png",';
      echo '  logo_mask: true,';
      echo '  logo_margin: "0.1em",';
      echo "  background: \"/static/$pleroma_background_image\",";
      echo '  redirect_root_no_login: "/main/all",';
      echo '  redirect_root_login: "/main/friends",';
      echo '  show_instance_panel: true,';
      echo '  collapse_message_with_subject: true,';
      echo '  formatting_options_enabled: true,';
      echo '  hide_user_stats: true,';
      echo '  scope_options_enabled: true';
      echo '';
      echo 'config :pleroma, :activitypub,';
      echo '  accept_blocks: true,';
      echo '  unfollow_blocked: true,';
      echo '  outgoing_blocks: true,';
      echo '  follow_handshake_timeout: 500';
      echo '';
      echo 'config :pleroma, :http_security,';
      echo "  enabled: ${pleroma_http_security},";
      echo '  sts: false,';
      echo '  sts_max_age: 31_536_000,';
      echo '  ct_max_age: 2_592_000,';
      echo '  referrer_policy: "same-origin"';
      echo '';
      echo 'config :cors_plug,';
      echo '  max_age: 86_400,';
      echo '  methods: ["POST", "PUT", "DELETE", "GET", "PATCH", "OPTIONS"],';
      echo '  expose: [';
      echo '    "Link",';
      echo '    "X-RateLimit-Reset",';
      echo '    "X-RateLimit-Limit",';
      echo '    "X-RateLimit-Remaining",';
      echo '    "X-Request-Id",';
      echo '    "Idempotency-Key"';
      echo '  ],';
      echo '  credentials: true,';
      echo '  headers: ["Authorization", "Content-Type", "Idempotency-Key"]';
      echo '';
      echo 'try do';
      echo '  # import_config "dev.secret.exs"';
      echo 'rescue';
      # shellcheck disable=SC2028
      echo '  _-> IO.puts("!!! RUNNING IN LOCALHOST DEV MODE! !!!\nFEDERATION WONT WORK UNTIL YOU CONFIGURE A dev.secret.exs")';
      echo 'end'; } > "$config_filename"
}

function pleroma_create_database {
    if [ -f "$IMAGE_PASSWORD_FILE" ]; then
        PLEROMA_ADMIN_PASSWORD="$(printf "%s" "$(cat "$IMAGE_PASSWORD_FILE")")"
    else
        if [ ! "$PLEROMA_ADMIN_PASSWORD" ]; then
            PLEROMA_ADMIN_PASSWORD="$(create_password "${MINIMUM_PASSWORD_LENGTH}")"
        fi
    fi
    if [ ! "$PLEROMA_ADMIN_PASSWORD" ]; then
        return
    fi

    systemctl restart postgresql
    add_postgresql_user pleroma "$PLEROMA_ADMIN_PASSWORD" encrypted
    run_system_query_postgresql "create database pleroma;"
    # temporarily allow the user to create databases
    run_system_query_postgresql "ALTER USER pleroma CREATEDB;"
    run_system_query_postgresql "ALTER USER pleroma SUPERUSER;"
    run_system_query_postgresql "GRANT ALL ON ALL tables IN SCHEMA public TO pleroma;"
    run_system_query_postgresql "GRANT ALL ON ALL sequences IN SCHEMA public TO pleroma;"
    run_system_query_postgresql "CREATE EXTENSION citext;"
    run_system_query_postgresql "set statement_timeout to 40000;"

    read_config_param "PLEROMA_SECRET_KEY"
    if [ ${#PLEROMA_SECRET_KEY} -lt 64 ]; then
        PLEROMA_SECRET_KEY="$(create_random_string 30)$(create_random_string 30)$(create_random_string 30)"
        if [ ${#PLEROMA_SECRET_KEY} -lt 64 ]; then
            pleroma_create_database_failed
            echo $'Pleroma secret key not created'
            exit 67
        fi
        write_config_param "PLEROMA_SECRET_KEY" "$PLEROMA_SECRET_KEY"
    fi

    pleroma_create_signing_salt

    if [ ! -d $PLEROMA_DIR/config ]; then
        echo $"Missing directory $PLEROMA_DIR/config"
        exit 78
    fi
    if [ ! -f $PLEROMA_DIR/config/dev.exs ]; then
        echo $"Did not find $PLEROMA_DIR/config/dev.exs"
        exit 78
    fi

    pleroma_create_config $pleroma_secret

    cd "$PLEROMA_DIR" || exit 67
    chown -R pleroma:pleroma $PLEROMA_DIR/*
    if ! sudo -u pleroma mix local.rebar --force; then
        pleroma_create_database_failed
        echo $'mix local.rebar failed'
        exit 73
    fi
    sudo -u pleroma mix local.hex --force
    sudo -u pleroma mix deps.compile mimerl
    systemctl restart postgresql
    if ! sudo -u pleroma mix ecto.create --force; then
        pleroma_create_database_failed
        echo $'mix ecto.create failed'
        exit 83
    fi
    if ! sudo -u pleroma mix ecto.migrate --force; then
        pleroma_create_database_failed
        echo $'mix ecto.migrate failed'
        exit 73
    fi

    # revoke the ability to create databases for this user
    run_system_query_postgresql "ALTER USER pleroma NOSUPERUSER;"
    run_system_query_postgresql "ALTER USER pleroma NOCREATEDB;"
}

function reconfigure_pleroma {
    echo -n ''
}

function pleroma_set_background_image {
    PLEROMA_DOMAIN_NAME=$(get_completion_param "pleroma domain")

    data=$(mktemp 2>/dev/null)
    dialog --title $"Pleroma" \
           --backtitle $"Freedombone Control Panel" \
           --inputbox $'Set a background image URL' 10 60 2>"$data"
    sel=$?
    case $sel in
        0)
            temp_background=$(<"$data")
            if [ ${#temp_background} -gt 0 ]; then
                PLEROMA_BACKGROUND_IMAGE_URL="$temp_background"
                write_config_param "PLEROMA_BACKGROUND_IMAGE_URL" "$PLEROMA_BACKGROUND_IMAGE_URL"
                if [[ $(pleroma_set_background_image_from_url $PLEROMA_DIR "$PLEROMA_DOMAIN_NAME" "$PLEROMA_BACKGROUND_IMAGE_URL" "$PLEROMA_TITLE" | tail -n 1) == "0" ]]; then
                    chown -R pleroma:pleroma "$PLEROMA_DIR/priv/static/static"
                    pleroma_recompile

                    dialog --title $"Set Pleroma login background" \
                           --msgbox $"The background image has been set" 6 60
                fi
            fi
           ;;
    esac
    rm -f "$data"
}

function pleroma_set_title {
    data=$(mktemp 2>/dev/null)
    dialog --title $"Pleroma" \
           --backtitle $"Freedombone Control Panel" \
           --inputbox $'Set a title' 10 60 2>"$data"
    sel=$?
    case $sel in
        0)
            new_title=$(<"$data")
            if [ ${#new_title} -gt 0 ]; then
                PLEROMA_TITLE="$new_title"
                PLEROMA_DOMAIN_NAME=$(get_completion_param "pleroma domain")
                write_config_param "PLEROMA_TITLE" "$PLEROMA_TITLE"
                sed -i "s|\"name\":.*|\"name\": \"${PLEROMA_TITLE}\",|g" $PLEROMA_DIR/static/config.json
                sed -i "s|\"name\":.*|\"name\": \"${PLEROMA_TITLE}\",|g" $PLEROMA_DIR/priv/static/static/config.json
                sed -i "s|name: .*|name: \"${PLEROMA_TITLE}\",|g" $PLEROMA_DIR/config/config.exs
                systemctl restart pleroma
                dialog --title $"Set Pleroma title" \
                       --msgbox $"The title has been set" 6 60
            fi
           ;;
    esac
    rm -f "$data"
}

function pleroma_set_expire_months {
    PLEROMA_DOMAIN_NAME=$(get_completion_param "pleroma domain")
    read_config_param "PLEROMA_DOMAIN_NAME"
    read_config_param "PLEROMA_EXPIRE_MONTHS"

    data=$(mktemp 2>/dev/null)
    dialog --title $"Pleroma" \
           --backtitle $"Freedombone Control Panel" \
           --inputbox $'Set an expiry period for posts in months. Anything older will be deleted. Lower values help to keep the database size small and as fast as possible.' 12 60 "$PLEROMA_EXPIRE_MONTHS" 2>"$data"
    sel=$?
    case $sel in
        0)
            new_expiry_months=$(<"$data")
            if [ ${#new_expiry_months} -gt 0 ]; then
                # should contain no spaces
                if [[ "$new_expiry_months" == *" "* ]]; then
                    rm -f "$data"
                    return
                fi
                # should be a number
                re='^[0-9]+$'
                if ! [[ $new_expiry_months =~ $re ]] ; then
                    rm -f "$data"
                    return
                fi
                # set the new value
                PLEROMA_EXPIRE_MONTHS=$new_expiry_months
                write_config_param "PLEROMA_EXPIRE_MONTHS" "$PLEROMA_EXPIRE_MONTHS"

                expire_pleroma_posts "$PLEROMA_DOMAIN_NAME" "$PLEROMA_EXPIRE_MONTHS"
                create_pleroma_blocklist

                dialog --title $"Set Pleroma post expiry period" \
                       --msgbox $"Expiry period set to $PLEROMA_EXPIRE_MONTHS months" 6 60
            fi
           ;;
    esac
    rm -f "$data"
}

function pleroma_disable_registrations {
    dialog --title $"Disable new Pleroma user registrations" \
           --backtitle $"Freedombone Control Panel" \
           --yesno $"\\nDo you wish to disable new registrations?" 10 60
    sel=$?
    case $sel in
        0) sed -i 's|registrations_open: true|registrations_open: false|g' $PLEROMA_DIR/config/config.exs
           sed -i 's|registrations_open: True|registrations_open: false|g' $PLEROMA_DIR/config/config.exs
           sed -i 's|"registrationOpen": true|"registrationOpen": false|g' $PLEROMA_DIR/priv/static/static/config.json
           sed -i 's|"registrationOpen": True|"registrationOpen": false|g' $PLEROMA_DIR/priv/static/static/config.json
           ;;
        1) sed -i 's|registrations_open: false|registrations_open: true|g' $PLEROMA_DIR/config/config.exs
           sed -i 's|registrations_open: False|registrations_open: true|g' $PLEROMA_DIR/config/config.exs
           sed -i 's|"registrationOpen": false|"registrationOpen": true|g' $PLEROMA_DIR/priv/static/static/config.json
           sed -i 's|"registrationOpen": False|"registrationOpen": true|g' $PLEROMA_DIR/priv/static/static/config.json
           ;;
        255) return;;
    esac
    pleroma_recompile
}

function pleroma_add_emoji {
    data=$(mktemp 2>/dev/null)
    dialog --backtitle $"Freedombone Control Panel" \
           --title $"Add Custom Emoji" \
           --form "\\n" 8 75 2 \
           $"Shortcode:" 1 1 "" 1 18 16 15 \
           $"ImageURL:" 2 1 "" 2 18 512 10000 \
           2> "$data"
    sel=$?
    case $sel in
        1) rm -f "$data"
           return;;
        255) rm -f "$data"
             return;;
    esac
    shortcode=$(sed -n 1p < "$data")
    image_url=$(sed -n 2p < "$data")
    rm -f "$data"
    if [ ${#shortcode} -lt 2 ]; then
        return
    fi
    if [ ${#image_url} -lt 2 ]; then
        return
    fi
    if [[ "$image_url" != *'.'* ]]; then
        return
    fi
    if [[ "$image_url" != *'.png' && "$image_url" != *'.jpg' && "$image_url" != *'.jpeg' && "$image_url" != *'.gif' ]]; then
        dialog --title $"Add Custom Emoji" \
               --msgbox $"The image must be png/jpg/gif format" 6 60
        return
    fi
    if [[ "$shortcode" == *':'* || "$shortcode" == *' '* || "$shortcode" == *'.'* || "$shortcode" == *'!'* ]]; then
        dialog --title $"Add Custom Emoji" \
               --msgbox $"The shortcode contains invalid characters" 6 60
        return
    fi

    image_extension='png'
    if [[ "$image_url" == *'.jpg' || "$image_url" == *'.jpeg' ]]; then
        image_extension='jpg'
    fi
    if [[ "$image_url" == *'.gif' ]]; then
        image_extension='gif'
    fi

    if [ ! -d $PLEROMA_DIR/priv/static/emoji ]; then
        mkdir -p $PLEROMA_DIR/priv/static/emoji
    fi

    image_filename=$PLEROMA_DIR/priv/static/emoji/${shortcode}.${image_extension}
    if [ -f "$image_filename" ]; then
        mv "$image_filename" "${image_filename}.prev"
    fi
    wget "$image_url" -O "$image_filename"
    if [ ! -f "$image_filename" ]; then
        if [ -f "${image_filename}.prev" ]; then
            mv "${image_filename}.prev" "${image_filename}"
        fi
        dialog --title $"Add Custom Emoji" \
               --msgbox $"Unable to download the image" 6 60
        return
    fi

    if [[ "$image_url" == *'.jpg' || "$image_url" == *'.jpeg' || "$image_url" == *'.gif' ]]; then
        convert "$image_filename" -resize "$emoji_resolution" "$PLEROMA_DIR/priv/static/emoji/${shortcode}.png"
        if [ ! -f "$PLEROMA_DIR/priv/static/emoji/${shortcode}.png" ]; then
            dialog --title $"Add Custom Emoji" \
                   --msgbox $"Unable to convert empji image to png format" 6 60
            return
        fi

        # remove the original
        rm "$image_filename"

        image_extension='png'
        image_filename=$PLEROMA_DIR/priv/static/emoji/${shortcode}.${image_extension}
    else
        convert "$image_filename" -resize "$emoji_resolution" "$image_filename"
    fi

    if ! grep -q "${shortcode}," $PLEROMA_DIR/config/emoji.txt; then
        echo "${shortcode}, /emoji/${shortcode}.${image_extension}" >> $PLEROMA_DIR/config/emoji.txt
    else
        sed -i "s|${shortcode},.*|${shortcode}, /emoji/${shortcode}.${image_extension}|g" $PLEROMA_DIR/config/emoji.txt
    fi

    chown -R pleroma:pleroma $PLEROMA_DIR
    clear
    echo ''
    echo $'Recompiling Pleroma with the new emoji'
    systemctl stop pleroma
    pleroma_recompile

    dialog --title $"Add Custom Emoji" \
           --msgbox $"Custom emoji :${shortcode}: has been added" 6 70
}

function pleroma_whitelist {
    whitelist_filename=$PLEROMA_DIR/whitelist.txt
    if [ ! -f $whitelist_filename ]; then
        { echo '# Domain whitelist';
          echo '';
          echo '# If you add domains to this list then pleroma will be';
          echo '# restricted to federating only with those domains';
          echo '';
          echo '# Do not include your own instance domain in this list!';
          echo ''; } > $whitelist_filename
    fi

    editor $whitelist_filename

    first_line=1
    domain_list=
    while read -r domain; do
        if [[ "$domain" == *'#'* || "$domain" != *'.'* ]]; then
            continue
        fi

        if [ ! $first_line ]; then
            domain_list="${domain_list}, \"$domain\""
        else
            domain_list="\"$domain\""
        fi

        first_line=
    done <$whitelist_filename

    if [ ! "$domain_list" ]; then
        sed -i "s|accept: .*|accept: [],|g" $pleroma_secret
    else
        if [[ "$ONION_ONLY" == 'no' ]]; then
            sed -i "s|accept: .*|accept: [ \"$PLEROMA_DOMAIN_NAME\", ${domain_list} ],|g" $pleroma_secret
        else
            pleroma_onion_domain=$(cat /var/lib/tor/hidden_service_pleroma/hostname)
            sed -i "s|accept: .*|accept: [ \"$pleroma_onion_domain\", ${domain_list} ],|g" $pleroma_secret
        fi
    fi

    pleroma_recompile

    if [ "$domain_list" ]; then
        dialog --title $"Pleroma Whitelist" \
               --msgbox $"\\nYou are now only federating with the whitelisted domains" 8 60
    else
        dialog --title $"Pleroma Whitelist" \
               --msgbox $"\\nWhitelist is disabled" 8 40
    fi
}

function configure_interactive_pleroma {
    read_config_param ONION_ONLY
    read_config_param PLEROMA_DOMAIN_NAME
    read_config_param PLEROMA_EXPIRE_MONTHS
    while true
    do
        chatenabled=
        enablechatstr=$'Enable chat system'
        if grep -q ':chat, enabled: true' $PLEROMA_DIR/config/config.exs; then
            chatenabled=1
            enablechatstr=$'Disable chat system'
        fi

        pleromatorstr=$'Enable routing through Tor for onion addresses'
        if grep -q '9050' $pleroma_secret; then
            pleromatorstr=$'Disable routing through Tor'
        fi

        W=(1 $"Set a background image"
           2 $"Set the title"
           3 $"Disable new account registrations"
           4 $"Add a custom emoji"
           5 $"Set post expiry period (currently $PLEROMA_EXPIRE_MONTHS months)"
           6 "$enablechatstr"
           7 "$pleromatorstr"
           8 $'Domain whitelist')

        # shellcheck disable=SC2068
        selection=$(dialog --backtitle $"Freedombone Administrator Control Panel" --title $"Pleroma" --menu $"Choose an operation, or ESC to exit:" 15 60 8 "${W[@]}" 3>&2 2>&1 1>&3)

        if [ ! "$selection" ]; then
            break
        fi

        case $selection in
            1) pleroma_set_background_image;;
            2) pleroma_set_title;;
            3) pleroma_disable_registrations;;
            4) pleroma_add_emoji;;
            5) pleroma_set_expire_months;;
            6) if [ $chatenabled ]; then
                   pleroma_enable_chat false
               else
                   pleroma_enable_chat true
               fi
               ;;
            7) if grep -q '9050' $pleroma_secret; then
                   pleroma_disable_tor
               else
                   pleroma_enable_tor
               fi
               ;;
            8) pleroma_whitelist;;
        esac
    done
}

function pleroma_disable_tor {
    if grep -q '9050' $pleroma_secret; then
        sed -i '/9050/d' $pleroma_secret
        sed -i 's|# config :pleroma, :http, proxy_url:|config :pleroma, :http, proxy_url:|g' $PLEROMA_DIR/config/config.exs
        pleroma_recompile
    fi
}

function pleroma_enable_tor {
    pleroma_tor_update=

    if ! grep -q '9050' $pleroma_secret; then
        pleroma_tor_update=1
    fi

    if ! grep -q '# config :pleroma, :http, proxy_url:' $PLEROMA_DIR/config/config.exs; then
        pleroma_tor_update=1
    fi

    if [ ! $pleroma_tor_update ]; then
        return
    fi

    if ! grep -q '9050' $pleroma_secret; then
        sed -i '/url:/a config :pleroma, :http, proxy_url: {:socks5, :localhost, 9050}' $pleroma_secret
    fi

    if ! grep -q '# config :pleroma, :http, proxy_url:' $PLEROMA_DIR/config/config.exs; then
        sed -i 's|config :pleroma, :http, proxy_url:|# config :pleroma, :http, proxy_url:|g' $PLEROMA_DIR/config/config.exs
    fi

    pleroma_recompile
}

function pleroma_create_signing_salt {
    read_config_param "PLEROMA_SIGNING_SALT"
    if [ ${#PLEROMA_SIGNING_SALT} -lt 8 ]; then
        PLEROMA_SIGNING_SALT="$(create_random_string 8)"
        if [ ${#PLEROMA_SIGNING_SALT} -lt 8 ]; then
            echo $'Warning: Pleroma signing salt not created'
            return
        fi
        write_config_param "PLEROMA_SIGNING_SALT" "$PLEROMA_SIGNING_SALT"
    fi
}

function upgrade_pleroma {
    pleroma_installing=

    read_config_param PLEROMA_DOMAIN_NAME
    read_config_param PLEROMA_EXPIRE_MONTHS

    expire_pleroma_posts "$PLEROMA_DOMAIN_NAME" "$PLEROMA_EXPIRE_MONTHS"
    create_pleroma_blocklist

    pleroma_create_signing_salt

    # if the registrations state doesn't exist in the secret config then add it
    if ! grep -q 'registrations_open' $pleroma_secret; then
        if grep -q '"registrationOpen": false' $PLEROMA_DIR/priv/static/static/config.json; then
            pleroma_setting_registration 0
        else
            pleroma_setting_registration 1
        fi
    fi

    # if there is disagreement in the registrations state then
    # default to the value used in config.json
    if grep -q '"registrationOpen": false' $PLEROMA_DIR/priv/static/static/config.json; then
        if grep -q 'registrations_open: true' $PLEROMA_DIR/config/config.exs; then
            pleroma_setting_registration 0
        fi
    fi

    #pleroma_enable_tor

    CURR_PLEROMA_COMMIT=$(get_completion_param "pleroma commit")
    if [[ "$CURR_PLEROMA_COMMIT" == "$PLEROMA_COMMIT" ]]; then
        return
    fi

    pleroma_registrations=open
    if grep -q 'registrations_open: false' $PLEROMA_DIR/config/config.exs; then
        pleroma_registrations=
    fi

    pleroma_chat_enabled=1
    if grep -q ':chat, enabled: false' $PLEROMA_DIR/config/config.exs; then
        pleroma_chat_enabled=
    fi

    # make a copy of the configuration
    cp $PLEROMA_DIR/priv/static/static/config.json $PLEROMA_DIR/priv/static/static/config_prev.json

    if [ -f $PLEROMA_DIR/config/emoji.txt ]; then
        cp $PLEROMA_DIR/config/emoji.txt $PLEROMA_DIR/config/emoji_prev.txt
    fi

    $UPDATE_PACKAGES
    $INSTALL_PACKAGES --only-upgrade esl-erlang
    $INSTALL_PACKAGES --only-upgrade elixir erlang-xmerl erlang-dev erlang-parsetools

    function_check set_repo_commit
    set_repo_commit $PLEROMA_DIR "pleroma commit" "$PLEROMA_COMMIT" $PLEROMA_REPO
    chown -R pleroma:pleroma $PLEROMA_DIR

    # restore the configuration
    cp $PLEROMA_DIR/priv/static/static/config_prev.json $PLEROMA_DIR/priv/static/static/config.json
    chown pleroma:pleroma $PLEROMA_DIR/priv/static/static/config.json

    if [ -f $PLEROMA_DIR/config/emoji_prev.txt ]; then
        cp $PLEROMA_DIR/config/emoji_prev.txt $PLEROMA_DIR/config/emoji.txt
        chown pleroma:pleroma $PLEROMA_DIR/config/emoji.txt
        rm cp $PLEROMA_DIR/config/emoji_prev.txt
    fi

    sudo -u pleroma mix deps.get

    sed -i 's|collapse_message_with_subject:.*|collapse_message_with_subject: true,|g' $pleroma_secret

    if ! grep -q 'level: :warn' $pleroma_secret; then
        echo $'Changing log level to warn'
        sed -i "s|config :logger,.*|config :logger, :console, format: \"[\$level] \$message\\\n\", level: :warn|g" $pleroma_secret
    fi

    if ! grep -q 'mrf_transparency: false' $pleroma_secret; then
        echo $'Switched to private mrf rules'
        sed -i 's|mrf_transparency:.*|mrf_transparency: false,|g' $pleroma_secret
    fi

    if ! grep -q 'signing_salt:' $pleroma_secret; then
        echo $'Adding signing salt'
        read_config_param PLEROMA_SIGNING_SALT
        if [ "$PLEROMA_SIGNING_SALT" ]; then
            sed -i "/secret_key_base:/a signing_salt: \"${PLEROMA_SIGNING_SALT}\"," $pleroma_secret
            sed -i 's|signing_salt:|  signing_salt:|g' $pleroma_secret
        fi
    fi

    if ! grep -q "config :pleroma, :instance" $pleroma_secret; then
        sed -i '/# begin filtering/a   rewrite_policy: Pleroma.Web.ActivityPub.MRF.SimplePolicy' $pleroma_secret
        sed -i 's|rewrite_policy: Pleroma.Web.ActivityPub|  rewrite_policy: Pleroma.Web.ActivityPub|g' $pleroma_secret
        sed -i '/# begin filtering/a finmoji_enabled: true,'; $pleroma_secret
        sed -i 's|finmoji_enabled:|  finmoji_enabled:|g' $pleroma_secret
        sed -i '/# begin filtering/a quarantined_instances: [],'; $pleroma_secret
        sed -i 's|quarantined_instances:|  quarantined_instances:|g' $pleroma_secret
        sed -i '/# begin filtering/a mrf_transparency: false,'; $pleroma_secret
        sed -i 's|mrf_transparency:|  mrf_transparency:|g' $pleroma_secret
        sed -i '/# begin filtering/a config :pleroma, :instance,' $pleroma_secret
    fi

    if ! grep -q "hide_user_stats" $pleroma_secret; then
        sed -i '/show_instance_panel/a hide_user_stats: true,' $pleroma_secret
        sed -i 's|hide_user_stats|  hide_user_stats|g' $pleroma_secret
    else
        sed -i 's|hide_user_stats:.*|hide_user_stats: true,|g' $pleroma_secret
    fi

    if ! grep -q "formatting_options_enabled" $pleroma_secret; then
        sed -i '/show_instance_panel/a formatting_options_enabled: true,' $pleroma_secret
        sed -i 's|formatting_options_enabled|  formatting_options_enabled|g' $pleroma_secret
    else
        sed -i 's|formatting_options_enabled:.*|formatting_options_enabled: true,|g' $pleroma_secret
    fi

    if ! grep -q "strip_exif" $pleroma_secret; then
        sed -i '/config :logger/a strip_exif: true' $pleroma_secret
        sed -i 's|strip_exif|  strip_exif|g' $pleroma_secret

        sed -i '/config :logger/a uploads: "uploads",' $pleroma_secret
        sed -i 's|uploads: "uploads"|  uploads: "uploads"|g' $pleroma_secret

        sed -i '/config :logger/a config :pleroma, Pleroma.Upload,' $pleroma_secret
        sed -i 's|config :pleroma, Pleroma.Upload|  config :pleroma, Pleroma.Upload|g' $pleroma_secret
    fi

    if ! grep -q "mrf_rejectnonpublic" $pleroma_secret; then
        sed -i '/config :pleroma, :fe/i config :pleroma, :mrf_rejectnonpublic,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i allow_followersonly: true,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i allow_direct: true' $pleroma_secret
    fi

    if ! grep -q "mrf_hellthread" $pleroma_secret; then
        sed -i "/config :pleroma, :fe/i config :pleroma, :mrf_hellthread, threshold: $maximum_tagged_thread_participants" $pleroma_secret
    fi

    if [ ! $pleroma_registrations ]; then
        sed -i 's|registrations_open: true|registrations_open: false|g' $PLEROMA_DIR/config/config.exs
        sed -i 's|registrations_open: True|registrations_open: false|g' $PLEROMA_DIR/config/config.exs
    fi

    if [ ! $pleroma_chat_enabled ]; then
        sed -i 's|config :pleroma, :chat.*|config :pleroma, :chat, enabled: false|g' $PLEROMA_DIR/config/config.exs
    else
        sed -i 's|config :pleroma, :chat.*|config :pleroma, :chat, enabled: true|g' $PLEROMA_DIR/config/config.exs
    fi

    if ! grep -q ":http_security," $pleroma_secret; then
        sed -i '/config :pleroma, :fe/i config :pleroma, :http_security,' $pleroma_secret
        if [[ "$ONION_ONLY" == 'no' ]]; then
            sed -i '/config :pleroma, :fe/i enabled: true,' $pleroma_secret
        else
            sed -i '/config :pleroma, :fe/i enabled: false,' $pleroma_secret
        fi
        sed -i '/config :pleroma, :fe/i sts: false,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i sts_max_age: 31_536_000,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i ct_max_age: 2_592_000,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i referrer_policy: "same-origin"' $pleroma_secret
    fi

    if ! grep -q ":cors_plug," $pleroma_secret; then
        sed -i '/config :pleroma, :fe/i config :cors_plug,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   max_age: 86_400,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   methods: ["POST", "PUT", "DELETE", "GET", "PATCH", "OPTIONS"],' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   expose: [' $pleroma_secret
        sed -i '/config :pleroma, :fe/i     "Link",' $pleroma_secret
        sed -i '/config :pleroma, :fe/i     "X-RateLimit-Reset",' $pleroma_secret
        sed -i '/config :pleroma, :fe/i     "X-RateLimit-Limit",' $pleroma_secret
        sed -i '/config :pleroma, :fe/i     "X-RateLimit-Remaining",' $pleroma_secret
        sed -i '/config :pleroma, :fe/i     "X-Request-Id",' $pleroma_secret
        sed -i '/config :pleroma, :fe/i     "Idempotency-Key"' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   ],' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   credentials: true,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   headers: ["Authorization", "Content-Type", "Idempotency-Key"]' $pleroma_secret
    fi

    if ! grep -q ":activitypub," $pleroma_secret; then
        sed -i '/config :pleroma, :fe/i config :pleroma, :activitypub,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   accept_blocks: true,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   unfollow_blocked: true,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   outgoing_blocks: true,' $pleroma_secret
        sed -i '/config :pleroma, :fe/i   follow_handshake_timeout: 500' $pleroma_secret
    fi

    pleroma_enable_web_push_encryption

    # if there is a difference between registrations state then default to the one in the secret config
    if grep -q 'registrations_open: false' "$pleroma_secret"; then
        if grep -q 'registrations_open: true' $PLEROMA_DIR/config/config.exs; then
            sed -i 's|registrations_open: true|registrations_open: false|g' $PLEROMA_DIR/config/config.exs
        fi
        if grep -q 'registrations_open: True' $PLEROMA_DIR/config/config.exs; then
            sed -i 's|registrations_open: True|registrations_open: false|g' $PLEROMA_DIR/config/config.exs
        fi
    fi

    pleroma_recompile

    # migrate database
    sudo -u pleroma mix deps.clean --build mime
    sudo -u pleroma mix ecto.migrate

    pleroma_custom_logo "$PLEROMA_DIR"

    expire_pleroma_posts "$PLEROMA_DOMAIN_NAME" "$PLEROMA_EXPIRE_MONTHS"
    create_pleroma_blocklist

    chown -R pleroma:pleroma $PLEROMA_DIR

    # database modification
    cd /etc/postgresql || exit 35
    sudo -u postgres psql pleroma -c "create extension if not exists pg_trgm"
    sudo -u postgres psql pleroma -c 'create extension if not exists "uuid-ossp"'

    # Handle inconsistent location of mix command
    # On x86 /usr/local/bin/mix, on arm /usr/bin/mix
    if [ -f /usr/bin/mix ]; then
        if grep -q '/usr/local/bin/mix' /etc/systemd/system/pleroma.service; then
            sed -i 's|/usr/local/bin/mix|/usr/bin/mix|g' /etc/systemd/system/pleroma.service
            systemctl daemon-reload
        fi
    fi

    systemctl restart pleroma

    if grep 'add_header' "/etc/nginx/sites-available/$PLEROMA_DOMAIN_NAME"; then
        sed -i '/add_header/d' "/etc/nginx/sites-available/$PLEROMA_DOMAIN_NAME"
        systemctl restart nginx
    fi
}

function backup_local_pleroma {
    PLEROMA_DOMAIN_NAME='pleroma'
    if grep -q "pleroma domain" "$COMPLETION_FILE"; then
        PLEROMA_DOMAIN_NAME=$(get_completion_param "pleroma domain")
    fi

    systemctl stop pleroma

    function_check suspend_site
    suspend_site "${PLEROMA_DOMAIN_NAME}"

    source_directory=$PLEROMA_DIR
    dest_directory=pleroma
    backup_directory_to_usb $source_directory $dest_directory

    USE_POSTGRESQL=1
    function_check backup_database_to_usb
    backup_database_to_usb pleroma

    function_check restart_site
    restart_site

    systemctl restart pleroma
}

function restore_local_pleroma {
    if ! grep -q "pleroma domain" "$COMPLETION_FILE"; then
        return
    fi
    PLEROMA_DOMAIN_NAME=$(get_completion_param "pleroma domain")
    if [ "$PLEROMA_DOMAIN_NAME" ]; then
        echo $"Restoring pleroma"
        temp_restore_dir=/root/temppleroma
        pleroma_dir=$PLEROMA_DIR

        systemctl stop pleroma

        PLEROMA_ONION_HOSTNAME=$(cat /var/lib/tor/hidden_service_pleroma/hostname)
        function_check pleroma_create_database
        pleroma_create_database

        USE_POSTGRESQL=1
        restore_database pleroma
        if [ -d $temp_restore_dir ]; then
            rm -rf $temp_restore_dir
        fi

        function_check restore_directory_from_usb
        restore_directory_from_usb $temp_restore_dir pleroma
        if [ -d $temp_restore_dir ]; then
            chown -R pleroma:pleroma $pleroma_dir
            rm -rf $temp_restore_dir
        fi

        pleroma_recompile

        echo $"Restore of pleroma complete"
    fi
}

function backup_remote_pleroma {
    echo -n ''
}

function restore_remote_pleroma {
    echo -n ''
}

function remove_pleroma {
    if [ ${#PLEROMA_DOMAIN_NAME} -eq 0 ]; then
        return
    fi
    systemctl stop pleroma
    systemctl disable pleroma
    rm /etc/systemd/system/pleroma.service

    userdel pleroma
    #remove_elixir

    function_check remove_nodejs
    remove_nodejs pleroma-backend

    read_config_param "PLEROMA_DOMAIN_NAME"
    read_config_param "MY_USERNAME"
    echo "Removing $PLEROMA_DOMAIN_NAME"
    nginx_dissite "$PLEROMA_DOMAIN_NAME"
    remove_certs "$PLEROMA_DOMAIN_NAME"

    if [ -d "/var/www/$PLEROMA_DOMAIN_NAME" ]; then
        rm -rf "/var/www/$PLEROMA_DOMAIN_NAME"
    fi
    if [ -f "/etc/nginx/sites-available/$PLEROMA_DOMAIN_NAME" ]; then
        rm "/etc/nginx/sites-available/$PLEROMA_DOMAIN_NAME"
    fi
    if [ -d $PLEROMA_DIR ]; then
        rm -rf $PLEROMA_DIR
    fi
    function_check drop_database_postgresql
    drop_database_postgresql pleroma
    function_check remove_onion_service
    remove_onion_service pleroma ${PLEROMA_ONION_PORT}
    remove_app pleroma
    remove_completion_param install_pleroma
    sed -i '/pleroma domain/d' "$COMPLETION_FILE"
    sed -i '/pleroma commit/d' "$COMPLETION_FILE"
    sed -i "/$blocking_script_file/d" /etc/crontab

    if [ -f /usr/bin/pleroma-blocking ]; then
        rm /usr/bin/pleroma-blocking
    fi

    if [ -f /usr/bin/pleroma-recompile ]; then
        rm /usr/bin/pleroma-recompile
    fi

    function_check remove_ddns_domain
    remove_ddns_domain "$PLEROMA_DOMAIN_NAME"
}

function install_pleroma {
    if [ ! $ONION_ONLY ]; then
        ONION_ONLY='no'
    fi

    pleroma_installing=1

    increment_app_install_progress

    $INSTALL_PACKAGES wget imagemagick

    increment_app_install_progress

    # We need elixir 1.4+ here, so the debian repo package won't do
    install_elixir

    increment_app_install_progress

    function_check install_nodejs
    install_nodejs pleroma-backend

    increment_app_install_progress

    install_postgresql

    increment_app_install_progress

    if [ ! -d "/var/www/${PLEROMA_DOMAIN_NAME}/htdocs" ]; then
        mkdir -p "/var/www/${PLEROMA_DOMAIN_NAME}/htdocs"
    fi
    if [ -d $PLEROMA_DIR ]; then
        rm -rf $PLEROMA_DIR
    fi

    # get the repo
    if [ -f /repos/pleroma/index.html ]; then
        mv /repos/pleroma /repos/pleroma-fe
    fi
    if [ -d /repos/pleroma ]; then
        mkdir -p $PLEROMA_DIR
        cp -r -p /repos/pleroma/. $PLEROMA_DIR
        cd "$PLEROMA_DIR" || exit 83
        git pull
    else
        function_check git_clone
        git_clone $PLEROMA_REPO $PLEROMA_DIR
    fi

    increment_app_install_progress

    if [ ! -d $PLEROMA_DIR ]; then
        echo $'Unable to clone pleroma backend repo'
        pleroma_installing=
        exit 78
    fi

    increment_app_install_progress

    # create user
    useradd -d $PLEROMA_DIR -s /bin/false pleroma

    increment_app_install_progress

    # checkout the commit
    cd "$PLEROMA_DIR" || exit 62
    git checkout $PLEROMA_COMMIT -b $PLEROMA_COMMIT
    set_completion_param "pleroma commit" "$PLEROMA_COMMIT"
    chown -R pleroma:pleroma $PLEROMA_DIR

    increment_app_install_progress

    # web config
    function_check add_ddns_domain
    add_ddns_domain "$PLEROMA_DOMAIN_NAME"

    PLEROMA_ONION_HOSTNAME=$(add_onion_service pleroma 80 ${PLEROMA_ONION_PORT})

    increment_app_install_progress

    pleroma_nginx_site=/etc/nginx/sites-available/$PLEROMA_DOMAIN_NAME
    if [[ $ONION_ONLY == "no" ]]; then
        function_check nginx_http_redirect
        nginx_http_redirect "$PLEROMA_DOMAIN_NAME" "index index.html"
        { echo '';
          echo 'proxy_cache_path /tmp/pleroma-media-cache levels=1:2 keys_zone=pleroma_media_cache:10m max_size=100m inactive=80m use_temp_path=off;';
          echo '';
          echo 'server {';
          echo '  listen 443 ssl http2;';
          echo '  #listen [::]:443 ssl http2;';
          echo "  server_name $PLEROMA_DOMAIN_NAME;";
          echo '';
          echo '  # Security'; } >> "$pleroma_nginx_site"
        function_check nginx_ssl
        nginx_ssl "$PLEROMA_DOMAIN_NAME"

        function_check nginx_security_options
        nginx_security_options "$PLEROMA_DOMAIN_NAME"
        nginx_robots "$PLEROMA_DOMAIN_NAME"

        { echo '';
          echo '  # Logs';
          echo '  access_log /dev/null;';
          echo '  error_log /dev/null;';
          echo '';
          echo "  root $PLEROMA_DIR;";
          echo '';
          echo '  index index.html;';
          echo '';
          echo '  gzip_vary on;';
          echo '  gzip_proxied any;';
          echo '  gzip_comp_level 6;';
          echo '  gzip_buffers 16 8k;';
          echo '  gzip_http_version 1.1;';
          echo '  gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/activity+json application/atom+xml;';
          echo '';
          echo '  location / {';
          echo '    client_max_body_size 15m;';
          echo '    client_body_buffer_size 15m;';
          echo '';
          echo '    limit_conn conn_limit_per_ip 50;';
          echo '    limit_req zone=req_limit_per_ip burst=50 nodelay;';
          echo '';
          echo '    proxy_http_version 1.1;';
          echo "    proxy_set_header Upgrade \$http_upgrade;";
          echo '    proxy_set_header Connection "upgrade";';
          echo "    proxy_set_header Host \$http_host;";
          echo '';
          echo "    proxy_pass http://localhost:$PLEROMA_PORT;";
          echo '  }';
          echo '';
          echo '  location /proxy {';
          echo '    client_max_body_size 15m;';
          echo '    client_body_buffer_size 15m;';
          echo '';
          echo '    limit_conn conn_limit_per_ip 50;';
          echo '    limit_req zone=req_limit_per_ip burst=50 nodelay;';
          echo '';
          echo '    proxy_cache pleroma_media_cache;';
          echo '    proxy_cache_lock on;';
          echo '    proxy_ignore_client_abort on;';
          echo "    proxy_pass http://localhost:$PLEROMA_PORT;";
          echo '  }';
          echo '  # include snippets/well-known.conf;';
          echo '}'; } >> "$pleroma_nginx_site"
    else
        echo 'proxy_cache_path /tmp/pleroma-media-cache levels=1:2 keys_zone=pleroma_media_cache:10m max_size=100m inactive=80m use_temp_path=off;' > "$pleroma_nginx_site"
        echo '' >> "$pleroma_nginx_site"
    fi
    { echo 'server {';
      echo "    listen 127.0.0.1:$PLEROMA_ONION_PORT default_server;";
      echo '    port_in_redirect off;';
      echo "    server_name $PLEROMA_ONION_HOSTNAME;";
      echo ''; } >> "$pleroma_nginx_site"
    function_check nginx_security_options
    nginx_security_options "$PLEROMA_DOMAIN_NAME"
    { echo '';
      echo '  # Logs';
      echo '  access_log /dev/null;';
      echo '  error_log /dev/null;';
      echo '';
      echo "  root $PLEROMA_DIR;";
      echo '';
      echo '  index index.html;';
      echo '';
      echo '  gzip_vary on;';
      echo '  gzip_proxied any;';
      echo '  gzip_comp_level 6;';
      echo '  gzip_buffers 16 8k;';
      echo '  gzip_http_version 1.1;';
      echo '  gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/activity+json application/atom+xml;';
      echo '';
      echo '  location / {';
      echo '    client_max_body_size 15m;';
      echo '    client_body_buffer_size 15m;';
      echo '';
      echo '    limit_conn conn_limit_per_ip 50;';
      echo '    limit_req zone=req_limit_per_ip burst=50 nodelay;';
      echo '';
      echo '    proxy_http_version 1.1;';
      echo "    proxy_set_header Upgrade \$http_upgrade;";
      echo '    proxy_set_header Connection "upgrade";';
      echo "    proxy_set_header Host \$http_host;";
      echo '';
      echo "    proxy_pass http://localhost:$PLEROMA_PORT;";
      echo '  }';
      echo '';
      echo '  location /proxy {';
      echo '    client_max_body_size 15m;';
      echo '    client_body_buffer_size 15m;';
      echo '';
      echo '    limit_conn conn_limit_per_ip 50;';
      echo '    limit_req zone=req_limit_per_ip burst=50 nodelay;';
      echo '';
      echo '    proxy_cache pleroma_media_cache;';
      echo '    proxy_cache_lock on;';
      echo '    proxy_ignore_client_abort on;';
      echo "    proxy_pass http://localhost:$PLEROMA_PORT;";
      echo '  }';
      echo '  # include snippets/well-known.conf;';
      echo '}'; } >> "$pleroma_nginx_site"

    if grep 'add_header' "$pleroma_nginx_site"; then
        sed -i '/add_header/d' "$pleroma_nginx_site"
    fi

    increment_app_install_progress

    # back end
    cd "$PLEROMA_DIR" || exit 24
    chown -R pleroma:pleroma "$PLEROMA_DIR/"*
    if ! sudo -u pleroma mix local.hex --force; then
        echo $'mix local.hex failed'
        pleroma_installing=
        exit 17
    fi

    increment_app_install_progress

    mix local.hex --force
    if ! sudo -u pleroma mix deps.get --force; then
        echo $'mix deps.get failed'
        pleroma_installing=
        exit 73
    fi

    increment_app_install_progress

    function_check pleroma_create_database
    pleroma_create_database

    increment_app_install_progress

    "${PROJECT_NAME}-pass" -u "$MY_USERNAME" -a pleroma -p "$PLEROMA_ADMIN_PASSWORD"

    # NOTE: we don't need to install the frontend separately,
    # since the backend contains a precompiled version of it

    increment_app_install_progress

    install_gnusocial_default_background "pleroma" "$PLEROMA_DOMAIN_NAME"
    if [ ! -f "$PLEROMA_DIR/priv/static/static/config.json" ]; then
        echo $"$PLEROMA_DIR/priv/static/static/config.json file missing"
        pleroma_installing=
        exit 32
    fi

    increment_app_install_progress

    { echo '{';
      echo "\"name\": \"$PLEROMA_TITLE\",";
      echo '"theme": "mammal",';
      echo '"background": "/static/bg_custom.jpg",';
      echo '"logo": "/static/logo_custom.png",';
      echo '"logoMask": true,';
      echo '"logoMargin": ".1em",';
      echo '"registrationOpen": false,';
      echo '"defaultPath": "/main/all",';
      echo '"chatDisabled": true,';
      echo '"showInstanceSpecificPanel": true,';
      echo '"redirectRootNoLogin": "/main/all",';
      echo '"redirectRootLogin": "/main/friends",';
      echo '"showWhoToFollowPanel": false,';
      echo '"scopeOptionsEnabled": true,';
      echo '"formattingOptionsEnabled": true,';
      echo '"media_proxy": true';
      echo '"collapseMessageWithSubject": true,';
      echo '"scopeCopy": false,';
      echo '"subjectLineBehavior": "email",';
      echo '"hidePostStats": true,';
      echo '"hideUserStats": true,';
      echo '"loginMethod": "password"';
      echo '}'; } > "$PLEROMA_DIR/priv/static/static/config.json"

    if [ "$PLEROMA_BACKGROUND_IMAGE_URL" ]; then
        pleroma_set_background_image_from_url $PLEROMA_DIR/priv/static "$PLEROMA_DOMAIN_NAME" "$PLEROMA_BACKGROUND_IMAGE_URL" "$PLEROMA_TITLE"
        chown -R pleroma:pleroma "$PLEROMA_DIR/priv/static/static"
    fi

    chown -R pleroma:pleroma "$PLEROMA_DIR/priv/static/static"

    increment_app_install_progress

    # Get certificate
    function_check create_site_certificate
    create_site_certificate "$PLEROMA_DOMAIN_NAME" 'yes'

    increment_app_install_progress

    function_check nginx_ensite
    nginx_ensite "$PLEROMA_DOMAIN_NAME"

    increment_app_install_progress

    systemctl restart postgresql

    increment_app_install_progress

    systemctl restart nginx

    increment_app_install_progress

    set_completion_param "pleroma domain" "$PLEROMA_DOMAIN_NAME"

    # We need to set up the url option again because it somehow gets
    # lost during mix compile
    if ! grep -q 'watchers: \[],' $pleroma_secret; then
        sed -i 's|watchers: \[\]|watchers: \[\],|g' $pleroma_secret
    fi
    if ! grep -q 'url:' $pleroma_secret; then
        if [[ $ONION_ONLY == 'no' ]]; then
            sed -i "/watchers: /a url: [host: \"$PLEROMA_DOMAIN_NAME\", scheme: \"https\", port: 443]" $pleroma_secret
        else
            sed -i "/watchers: /a url: [host: \"$PLEROMA_ONION_HOSTNAME\", scheme: \"http\", port: 80]" $pleroma_secret
        fi
    fi

    increment_app_install_progress

    create_pleroma_blocklist

    increment_app_install_progress

    # daemon
    { echo '[Unit]';
      echo 'Description=Pleroma social network';
      echo 'After=network.target postgresql.service';
      echo '';
      echo '[Service]';
      echo 'User=pleroma';
      echo "WorkingDirectory=$PLEROMA_DIR";
      echo "Environment=\"HOME=$PLEROMA_DIR\"";
      echo 'ExecStart=/usr/bin/mix phx.server';
      echo "ExecReload=/bin/kill \$MAINPID";
      echo 'KillMode=process';
      echo 'Restart=on-failure';
      echo 'PrivateTmp=true';
      echo 'PrivateDevices=false';
      echo 'NoNewPrivileges=true';
      echo 'CapabilityBoundingSet=~CAP_SYS_ADMIN';
      echo '';
      echo '[Install]';
      echo 'WantedBy=multi-user.target';
      echo 'Alias=pleroma.service'; } > /etc/systemd/system/pleroma.service


    # avoid mixed content warnings
    sed -i 's|config :pleroma, :media_proxy.*|config :pleroma, :media_proxy, enabled: false|g' $PLEROMA_DIR/config/config.exs
    sed -i 's|redirect_on_failure:.*|redirect_on_failure: false|g' $PLEROMA_DIR/config/config.exs
    sed -i 's|:chat, enabled:.*|:chat, enabled: false|g' $PLEROMA_DIR/config/config.exs

    # onion routing
    if ! grep -q '9050' $pleroma_secret; then
        sed -i '/url:/a config :pleroma, :http, proxy_url: {:socks5, :localhost, 9050}' $pleroma_secret
    fi
    sed -i 's|config :pleroma, :http, proxy_url:|# config :pleroma, :http, proxy_url:|g' $PLEROMA_DIR/config/config.exs

    # set registrations closed initially
    sed -i 's|registrations_open:.*|registrations_open: false,|g' $PLEROMA_DIR/config/config.exs
    sed -i 's|"registrationOpen":.*|"registrationOpen": false,|g' $PLEROMA_DIR/priv/static/static/config.json

    sed -i 's|"chatDisabled":.*|"chatDisabled": true,|g' $PLEROMA_DIR/priv/static/static/config.json

    increment_app_install_progress

    pleroma_set_permissions

    # Handle inconsistent location of mix command
    # On x86 /usr/local/bin/mix, on arm /usr/bin/mix
    if [ ! -f /usr/bin/mix ]; then
        if [ -f /usr/local/bin/mix ]; then
            if grep -q '/usr/bin/mix' /etc/systemd/system/pleroma.service; then
                sed -i 's|/usr/bin/mix|/usr/local/bin/mix|g' /etc/systemd/system/pleroma.service
            fi
        fi
    fi

    systemctl daemon-reload
    systemctl enable pleroma
    systemctl start pleroma

    increment_app_install_progress

    cd $PLEROMA_DIR || exit 19
    echo 'y' | sudo -u pleroma mix pleroma.user new "$MY_USERNAME" "$MY_EMAIL_ADDRESS" --bio $"Your bio goes here" --password "$PLEROMA_ADMIN_PASSWORD"

    increment_app_install_progress

    sudo -u pleroma mix set_moderator "$MY_USERNAME" true

    increment_app_install_progress

    pleroma_create_recompile_command

    pleroma_enable_web_push_encryption

    pleroma_installing=
    APP_INSTALLED=1
}

# NOTE: deliberately there is no "exit 0"