#!/bin/bash
#
# .---.                  .              .
# |                      |              |
# |--- .--. .-.  .-.  .-.|  .-. .--.--. |.-.  .-. .--.  .-.
# |    |   (.-' (.-' (   | (   )|  |  | |   )(   )|  | (.-'
# '    '     --'  --'  -' -  -' '  '   -' -'   -' '   -  --'
#
#                    Freedom in the Cloud
#
# synapse matrix server
#
# https://matrix.org/blog/2016/02/10/advanced-synapse-setup-with-lets-encrypt/
#
# Had no success in configuring this with Riot, and the identity server
# turned out to be centralised.
#   https://github.com/matrix-org/matrix-doc/issues/712
# Possibly it might become decentralised in future.
#
# License
# =======
#
# Copyright (C) 2016 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=''

IN_DEFAULT_INSTALL=0
SHOW_ON_ABOUT=0

SYNAPSE_PORT=8448
SYNAPSE_PASSWORD=
SYNAPSE_DIR=/etc/matrix-synapse
MATRIX_IRC_REPO="https://github.com/matrix-org/matrix-appservice-irc"

synapse_variables=(ONION_ONLY
                   MY_USERNAME
                   SYNAPSE_PASSWORD
                   DEFAULT_DOMAIN_NAME)

function install_matrix_irc_bridge {
    if [ ! -d /etc/matrix-synapse ]; then
        return
    fi
    if [ ! -d /etc/ngircd ]; then
        return
    fi

    function_check install_nodejs
    install_nodejs synapse

    if [ ! -d $INSTALL_DIR ]; then
        mkdir -p $INSTALL_DIR
    fi

    cd $INSTALL_DIR
    git_clone $MATRIX_IRC_REPO $INSTALL_DIR/matrix_irc_bridge
    cd $INSTALL_DIR/matrix_irc_bridge
    npm install
    if [ ! -f config.sample.yaml ]; then
        exit 623835
    fi

    IRC_PASSWORD=$(cat /etc/ngircd/ngircd.conf | grep "Password =" | head -n 1 | awk -F '=' '{print $2}')

    echo 'homeserver:' > $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '  url: "http://localhost:8008"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '  domain: "localhost"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo 'ircService:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '  servers:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo "    localhost:" >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo "      name: \"${PROJECT_NAME} IRC\"" >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo "      port: ${IRC_PORT}" >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      ssl: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      sslselfsign: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      password: "${IRC_PASSWORD}"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      sendConnectionMessages: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      quitDebounce:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        enabled: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        quitsPerSecond: 5' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        delayMs: 3600000 # 1h' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      botConfig:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        enabled: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        nick: "MatrixBot"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        joinChannelsIfNoUsers: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      privateMessages:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        enabled: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        federate: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      dynamicChannels:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        enabled: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        createAlias: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        published: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        joinRule: public' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        federate: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        aliasTemplate: "#irc_$CHANNEL"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      membershipLists:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        enabled: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        floodDelayMs: 10000' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        global:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '          ircToMatrix:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '            initial: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '            incremental: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '          matrixToIrc:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '            initial: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '            incremental: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        rooms:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '          - room: "!fuasirouddJoxtwfge:localhost"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '            matrixToIrc:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '              initial: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '              incremental: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        channels:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo "          - channel: \"#${PROJECT_NAME}\"" >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '            ircToMatrix:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '              initial: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '              incremental: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      mappings:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        "#thepub": ["!kieouiJuedJoxtVdaG:localhost"]' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      matrixClients:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        userTemplate: "@irc_$NICK"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        displayName: "$NICK (IRC)"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '      ircClients:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        nickTemplate: "$DISPLAY[m]"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        allowNickChanges: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        maxClients: 30' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        idleTimeout: 10800' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        reconnectIntervalMs: 5000' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '        lineLimit: 3' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '  ident:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    enabled: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    port: 1113' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '  logging:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    level: "debug"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    logfile: "debug.log"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    errfile: "errors.log"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    toConsole: true' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    maxFileSizeBytes: 134217728 # 128 MB' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    maxFiles: 5' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '  databaseUri: "nedb://data"' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '  debugApi:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    enabled: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    port: 11100' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '  provisioning:' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    enabled: false' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml
    echo '    requestTimeoutSeconds: 300' >> $INSTALL_DIR/matrix_irc_bridge/config.yaml

    /usr/bin/node $INSTALL_DIR/matrix_irc_bridge/app.js -r -f /etc/matrix-synapse/my_registration_file.yaml -u "http://${DEFAULT_DOMAIN_NAME}:9999" -c $INSTALL_DIR/matrix_irc_bridge/config.yaml -l my_bot

    if ! grep "my_registration_file.yaml" homeserver.yaml; then
        echo 'app_service_config_files: ["my_registration_file.yaml"]' >> homeserver.yaml
    fi

    echo '[Unit]' > /etc/systemd/system/matrix_irc_bridge.service
    echo 'Description=Matrix IRC Bridge' >> /etc/systemd/system/matrix_irc_bridge.service
    echo '' >> /etc/systemd/system/matrix_irc_bridge.service
    echo '[Service]' >> /etc/systemd/system/matrix_irc_bridge.service
    echo 'Type=simple' >> /etc/systemd/system/matrix_irc_bridge.service
    echo 'User=matrix-synapse' >> /etc/systemd/system/matrix_irc_bridge.service
    echo "WorkingDirectory=$INSTALL_DIR/matrix_irc_bridge" >> /etc/systemd/system/matrix_irc_bridge.service
    echo "ExecStart=/usr/bin/node $INSTALL_DIR/matrix_irc_bridge/app.js -c $INSTALL_DIR/matrix_irc_bridge/config.yaml -f /etc/matrix-synapse/my_registration_file.yaml -p 9999" >> /etc/systemd/system/matrix_irc_bridge.service
    echo 'Restart=always' >> /etc/systemd/system/matrix_irc_bridge.service
    echo 'RestartSec=3' >> /etc/systemd/system/matrix_irc_bridge.service
    echo '' >> /etc/systemd/system/matrix_irc_bridge.service
    echo '[Install]' >> /etc/systemd/system/matrix_irc_bridge.service
    echo 'WantedBy=multi-user.target' >> /etc/systemd/system/matrix_irc_bridge.service
    systemctl enable matrix_irc_bridge
    systemctl start matrix_irc_bridge
}

function can_install_synapse {
    check_architecture=$(uname -a)
    if [[ "$check_architecture" == *"amd64"* || "$check_architecture" == *"i386"* ]]; then
        echo "1"
    else
        echo "0"
    fi
}

function remove_user_synapse {
    remove_username="$1"

    ${PROJECT_NAME}-pass -u $remove_username --rmapp synapse

    # TODO
}

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

    ${PROJECT_NAME}-pass -u $new_username -a synapse -p "$new_user_password"

    cd $SYNAPSE_DIR
    register_new_matrix_user -c homeserver.yaml https://localhost:${SYNAPSE_PORT} -u "${new_username}" -p "${new_user_password}" -a
    echo '0'
}

function install_interactive_synapse {
    echo -n ''
    APP_INSTALLED=1
}

function change_password_synapse {
    curr_username="$1"
    new_user_password="$2"

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

function reconfigure_synapse {
    echo -n ''
}

function upgrade_synapse {
    echo -n ''
}

function backup_local_synapse {
    source_directory=$SYNAPSE_DIR
    if [ -d $source_directory ]; then
        systemctl stop synapse
        function_check backup_directory_to_usb
        backup_directory_to_usb $source_directory synapse
        source_directory=/var/lib/matrix-synapse
        if [ -d $source_directory ]; then
            backup_directory_to_usb $source_directory synapsedata
        fi
        systemctl start synapse
    fi
}

function restore_local_synapse {
    if [ -d $SYNAPSE_DIR ]; then
        systemctl stop synapse

        temp_restore_dir=/root/tempsynapse
        function_check restore_directory_from_usb
        restore_directory_from_usb $temp_restore_dir synapse
        cp -r $temp_restore_dir$SYNAPSE_DIR/* $SYNAPSE_DIR
        if [ ! "$?" = "0" ]; then
            function_check backup_unmount_drive
            backup_unmount_drive
            exit 725
        fi
        rm -rf $temp_restore_dir
        chown -R synapse:synapse $SYNAPSE_DIR

        temp_restore_dir=/root/tempsynapsedata
        restore_directory_from_usb $temp_restore_dir synapsedata
        cp -r $temp_restore_dir/var/lib/matrix-synapse/* /var/lib/matrix-synapse
        if [ ! "$?" = "0" ]; then
            function_check backup_unmount_drive
            backup_unmount_drive
            exit 36872
        fi
        rm -rf $temp_restore_dir
        chown -R synapse:synapse /var/lib/matrix-synapse

        systemctl start synapse
    fi
}

function backup_remote_synapse {
    source_directory=$SYNAPSE_DIR
    if [ -d $source_directory ]; then
        systemctl stop synapse
        function_check backup_directory_to_friend
        backup_directory_to_friend $source_directory synapse
        source_directory=/var/lib/matrix-synapse
        if [ -d $source_directory ]; then
            backup_directory_to_friend $source_directory synapsedata
        fi
        systemctl start synapse
    fi
}

function restore_remote_synapse {
    if [ -d $SYNAPSE_DIR ]; then
        systemctl stop synapse

        temp_restore_dir=/root/tempsynapse
        function_check restore_directory_from_friend
        restore_directory_from_friend $temp_restore_dir synapse
        cp -r $temp_restore_dir$SYNAPSE_DIR/* $SYNAPSE_DIR
        if [ ! "$?" = "0" ]; then
            exit 59262
        fi
        rm -rf $temp_restore_dir
        chown -R synapse:synapse $SYNAPSE_DIR

        temp_restore_dir=/root/tempsynapsedata
        restore_directory_from_friend $temp_restore_dir synapsedata
        cp -r $temp_restore_dir/var/lib/matrix-synapse/* /var/lib/matrix-synapse
        if [ ! "$?" = "0" ]; then
            exit 78335
        fi
        rm -rf $temp_restore_dir
        chown -R synapse:synapse /var/lib/matrix-synapse

        systemctl start synapse
    fi
}

function remove_synapse {
    systemctl stop matrix-synapse
    firewall_remove ${SYNAPSE_PORT}
    rm -rf $SYNAPSE_DIR
    apt-get -yq remove --purge matrix-synapse matrix-synapse-angular-client
    apt-get -yq autoremove

    rm /etc/apt/sources.list.d/synapse.list
    apt-get update

    if [ -f /etc/systemd/system/matrix_irc_bridge.service ]; then
        systemctl stop matrix_irc_bridge
        systemctl disable matrix_irc_bridge
        rm /etc/systemd/system/matrix_irc_bridge.service
        remove_nodejs synapse
        rm -rf $INSTALL_DIR/matrix_irc_bridge
    fi

    remove_completion_param install_synapse
    sed -i '/synapse/d' $COMPLETION_FILE
}

function install_synapse {
    if [[ "$(can_install_synapse)" == "0" ]]; then
        echo $'Matrix/Synapse can only be installed on i386 or amd64 architectures'
        exit 36734
    fi

    if [[ ${ONION_ONLY} == 'no' ]]; then
        # obtain a cert for the default domain
        if [[ "$(cert_exists ${DEFAULT_DOMAIN_NAME} pem)" == "0" ]]; then
            echo $'Obtaining certificate for the main domain'
            create_site_certificate ${DEFAULT_DOMAIN_NAME} 'yes'
        fi
    fi

    if [ ! -d /etc/prosody ]; then
        echo $'xmpp should be installed first'
        exit 67382
    fi

    apt-get -yq install build-essential python2.7-dev libffi-dev \
            python-pip python-setuptools sqlite3 \
            libssl-dev libjpeg-dev libxslt1-dev python-virtualenv curl

    curl -s https://matrix.org/packages/debian/repo-key.asc | apt-key add -
    echo "deb https://matrix.org/packages/debian/ ${DEBIAN_VERSION} main" | tee /etc/apt/sources.list.d/synapse.list
    apt-get update
    apt-get -yq install python-cffi
    apt-get -yq install python-nacl
    apt-get -yq install python-signedjson

    debconf-set-selections <<< "matrix-synapse matrix-synapse/server-name string $DEFAULT_DOMAIN_NAME"
    debconf-set-selections <<< "matrix-synapse matrix-synapse/server_name string $DEFAULT_DOMAIN_NAME"
    debconf-set-selections <<< "matrix-synapse matrix-synapse/report-stats boolean false"
    apt-get -yq install matrix-synapse
    if [ ! -d /etc/matrix-synapse ]; then
        exit 653835
    fi

    #apt-get -yq install matrix-synapse-angular-client
    #cp -av /etc/matrix-synapse/conf.d/webclient.yaml \
       #/etc/matrix-synapse/conf.d/webclient.yaml.orig
    #sed -e 's|,$||g' -i /etc/matrix-synapse/conf.d/webclient.yaml
    #cp -av  /etc/init.d/matrix-synapse /etc/init.d/matrix-synapse.orig
    #sed -e 's|chown $USER:nogroup $PIDFILE.*|chown $USER:nogroup $PIDFILE /var/lib/$NAME/media|g' -i /etc/init.d/matrix-synapse
    #diff -u /etc/init.d/matrix-synapse.orig /etc/init.d/matrix-synapse
    #cp -av /etc/matrix-synapse/homeserver.yaml /etc/matrix-synapse/homeserver.yaml.orig
    #sed -i 's|enable_registration: False|enable_registration: True|g' -i /etc/matrix-synapse/homeserver.yaml
    #rm -f /etc/matrix-synapse/conf.d/*.orig /etc/matrix-synapse/conf.d/*~

    update_default_domain
    systemctl stop matrix-synapse
    systemctl start matrix-synapse

    firewall_add synapse ${SYNAPSE_PORT}

    SYNAPSE_ONION_HOSTNAME=$(add_onion_service synapse ${SYNAPSE_PORT} ${SYNAPSE_PORT})
    if [ ! ${SYNAPSE_PASSWORD} ]; then
        if [ -f ${IMAGE_PASSWORD_FILE} ]; then
            SYNAPSE_PASSWORD="$(printf `cat $IMAGE_PASSWORD_FILE`)"
        else
            SYNAPSE_PASSWORD="$(create_password ${MINIMUM_PASSWORD_LENGTH})"
        fi
    fi

    add_user_synapse "${MY_USERNAME}" "${SYNAPSE_PASSWORD}"

    #install_matrix_irc_bridge

    APP_INSTALLED=1
}

# NOTE: deliberately no exit 0
