#!/bin/bash
#
# .---.                  .              .
# |                      |              |
# |--- .--. .-.  .-.  .-.|  .-. .--.--. |.-.  .-. .--.  .-.
# |    |   (.-' (.-' (   | (   )|  |  | |   )(   )|  | (.-'
# '    '     --'  --'  -' -  -' '  '   -' -'   -' '   -  --'
#
#                    Freedom in the Cloud
#
# This command is run on initial install in order to set up a mesh router
#
# License
# =======
#
# 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/>.

PROJECT_NAME='freedombone'

export TEXTDOMAIN=${PROJECT_NAME}-image-mesh
export TEXTDOMAINDIR="/usr/share/locale"

# The browser application to use
BROWSER=midori
BROWSER_OPTIONS='-p'

MY_USERNAME='fbone'
PEER_ID=
INSTALL_DIR=/root/build
INSTALL_LOG=/var/log/${PROJECT_NAME}.log

DEFAULT_USERNAME=fbone

TOX_NODES=
#TOX_NODES=(
#  '192.254.75.102,2607:5600:284::2,33445,951C88B7E75C867418ACDB5D273821372BB5BD652740BCDF623A4FA293E75D2F,Tox RELENG,US'
#  '144.76.60.215,2a01:4f8:191:64d6::1,33445,04119E835DF3E78BACF0F84235B300546AF8B936F035185E2A8E9E0A67C8924F,sonOfRa,DE'
#)

MESH_INSTALL_DIR=/var/lib
MESH_INSTALL_COMPLETED=/root/.mesh_setup_completed
MESH_INSTALL_SETUP=/root/.initial_mesh_setup
MESH_AMNESIC=/root/.amnesic
FIRST_BOOT=/home/$MY_USERNAME/.first_boot

# Tomb containing logs
TOMB_LOG_SIZE_MB=10

# tmp directory
TOMB_TMP_SIZE_MB=10

# size of the tomb used to store qtox settings
TOMB_TOX_SIZE_MB=10

# Tomb containing tox bootstrap
TOMB_TOX_BOOTSTRAP_SIZE_MB=10

MESH_INSTALL_DIR=/var/lib

IPFS_PORT=4001

CURRENT_BLOG_INDEX=/home/$MY_USERNAME/.blog-index

OPENVPN_SERVER_NAME="server"
OPENVPN_KEY_FILENAME='client.ovpn'
VPN_COUNTRY_CODE="US"
VPN_AREA="Apparent Free Speech Zone"
VPN_LOCATION="Freedomville"
VPN_ORGANISATION="Freedombone"
VPN_UNIT="Freedombone Unit"
STUNNEL_PORT=3439
VPN_TLS_PORT=553
VPN_MESH_TLS_PORT=653

SCUTTLEBOT_PORT=8010

CRYPTPAD_PORT=9003
CRYPTPAD_DIR=/etc/cryptpad

function enable_cryptpad {
    if [ ! -d $CRYPTPAD_DIR ]; then
        return
    fi

    # Set up the web server
    ln -s /etc/nginx/sites-available/cryptpad /etc/nginx/sites-enabled/cryptpad
    rm /etc/nginx/sites-enabled/default

    if [ ! -d $CRYPTPAD_DIR/customize/api ]; then
        mkdir -p $CRYPTPAD_DIR/customize/api
    fi
    wget 127.0.0.1:$CRYPTPAD_PORT/api/config -O $CRYPTPAD_DIR/customize/api/config
    if [ ! -f $CRYPTPAD_DIR/customize/api/config ]; then
        echo $'Unable to wget api/config'
        exit 89252
    fi
    chown -R cryptpad:cryptpad $CRYPTPAD_DIR
}

# Debian stretch has a problem where the formerly predictable wlan0 and eth0
# device names get assigned random names. This is a hacky workaround.
# Also adding net.ifnames=0 to kernel options on bootloader may work.
function enable_predictable_device_names {
    ln -s /dev/null /etc/udev/rules.d/80-net-setup-link.rules
    update-initramfs -u
}

function create_avahi_mesh_service {
    service_name=$1
    service_type=$2
    service_protocol=$3
    service_port=$4
    service_description="$5"

    if [ ! -d /etc/avahi ]; then
        echo $'create_avahi_mesh_service: avahi was not installed'
        exit 52925
    fi

    echo '<?xml version="1.0" standalone="no"?><!--*-nxml-*-->' > /etc/avahi/services/${service_name}.service
    echo '<!DOCTYPE service-group SYSTEM "avahi-service.dtd">' >> /etc/avahi/services/${service_name}.service
    echo '<service-group>' >> /etc/avahi/services/${service_name}.service
    echo "  <name replace-wildcards=\"yes\">%h ${service_type}</name>" >> /etc/avahi/services/${service_name}.service
    echo '  <service>' >> /etc/avahi/services/${service_name}.service
    echo "    <type>_${service_type}._${service_protocol}</type>" >> /etc/avahi/services/${service_name}.service
    echo "    <port>${service_port}</port>" >> /etc/avahi/services/${service_name}.service
    echo "    <txt-record>$service_description</txt-record>" >> /etc/avahi/services/${service_name}.service
    echo '  </service>' >> /etc/avahi/services/${service_name}.service
    echo '</service-group>' >> /etc/avahi/services/${service_name}.service
}

function create_ram_disk {
    ramdisk_size_mb=$1
    if [ ! -d /mnt/ramdisk ]; then
        mkdir -p /mnt/ramdisk
    fi
    if ! grep -q "ramdisk" /etc/fstab; then
        mount -t tmpfs -o size=${ramdisk_size_mb}m tmpfs /mnt/ramdisk
        echo "tmpfs       /mnt/ramdisk tmpfs   nodev,nosuid,noexec,nodiratime,size=${ramdisk_size_mb}M   0 0" >> /etc/fstab
        echo $"${ramdisk_size_mb}M ramdisk created for /tmp" >> $INSTALL_LOG
    fi
}

function make_root_read_only {
    if [ ! -d /home/$MY_USERNAME/Desktop ]; then
        if ! grep -q 'ro,subvol=@' /etc/fstab; then
            sed -i 's|subvol=@|ro,subvol=@|g' /etc/fstab
            echo $'Root filesystem set to read only' >> $INSTALL_LOG
        fi
    fi
}

function tmp_ram_disk {
    ramdisk_size_mb=$1
    if [ ! -d /tmp ]; then
        mkdir -p /tmp
    fi
    if ! grep -q '/tmp' /etc/fstab; then
        mount -t tmpfs -o size=${ramdisk_size_mb}m tmpfs /tmp
        echo "tmpfs       /tmp tmpfs   nodev,nosuid,noexec,nodiratime,size=${ramdisk_size_mb}M   0 0" >> /etc/fstab
    fi
}

function set_hostname {
    DEFAULT_DOMAIN_NAME="$1"

    echo "$DEFAULT_DOMAIN_NAME" > /etc/hostname
    echo "$DEFAULT_DOMAIN_NAME" > /etc/mailname
    hostname $DEFAULT_DOMAIN_NAME

    if grep -q "127.0.1.1" /etc/hosts; then
        sed -i "s/127.0.1.1.*/127.0.1.1       $DEFAULT_DOMAIN_NAME/g" /etc/hosts
    else
        echo "127.0.1.1  $DEFAULT_DOMAIN_NAME" >> /etc/hosts
    fi
}

function change_avahi_name {
    decarray=( 1 2 3 4 5 6 7 8 9 0 )
    PEER_ID=${decarray[$RANDOM%10]}${decarray[$RANDOM%10]}${decarray[$RANDOM%10]}${decarray[$RANDOM%10]}${decarray[$RANDOM%10]}${decarray[$RANDOM%10]}${decarray[$RANDOM%10]}${decarray[$RANDOM%10]}
    sed -i "s|#host-name=.*|host-name=P$PEER_ID|g" /etc/avahi/avahi-daemon.conf
    sed -i "s|host-name=.*|host-name=P$PEER_ID|g" /etc/avahi/avahi-daemon.conf
    set_hostname P$PEER_ID
    systemctl restart avahi-daemon

    echo "New avahi name for this peer is P$PEER_ID"
    echo $"avahi name changed to P${PEER_ID}.local" >> $INSTALL_LOG
}

function configure_toxcore {
    echo $'Configuring toxcore' >> $INSTALL_LOG

    TOXIC_FILE=$(cat /usr/share/${PROJECT_NAME}/apps/${PROJECT_NAME}-app-tox | grep "TOXIC_FILE=" | head -n 1 | awk -F '=' '{print $2}')

    if [ -f $MESH_AMNESIC ]; then
        # change to the amnesic mount
        sed -i 's|/var/lib/tox-bootstrapd|/media/tox-bootstrapd|g' /etc/tox-bootstrapd.conf
        systemctl stop tox-bootstrapd.service
        sed -i 's|WorkingDirectory=.*|WorkingDirectory=/media/tox-bootstrapd|g' /etc/systemd/system/tox-bootstrapd.service
        systemctl daemon-reload
        userdel -r tox-bootstrapd
        useradd --home-dir /media/tox-bootstrapd --create-home --system --shell /sbin/nologin --comment "Account to run Tox's DHT bootstrap daemon" --user-group tox-bootstrapd
        chmod 700 /media/tox-bootstrapd
    fi

    echo $'Enabling toxcore daemon' >> $INSTALL_LOG
    chmod +x /etc/systemd/system/tox-bootstrapd.service
    systemctl enable tox-bootstrapd.service

    echo $'Regenerating Tox bootstrap node keys' >> $INSTALL_LOG
    systemctl stop tox-bootstrapd.service
    if [ -f /var/lib/tox-bootstrapd/keys ]; then
        rm /var/lib/tox-bootstrapd/keys
    fi
    systemctl start tox-bootstrapd.service
    # sleep for a while so that the tox keys can be generated
    sleep 30
    TOX_BOOTSTRAP_ID_FILE=/var/lib/tox-bootstrapd/pubkey.txt
    if [ -f $MESH_AMNESIC ]; then
        TOX_BOOTSTRAP_ID_FILE=/media/tox-bootstrapd/pubkey.txt
    fi
    TOX_PUBLIC_KEY=$(cat /var/log/syslog | grep tox | grep "Public Key" | awk -F ' ' '{print $8}' | tail -1)
    if [ ${#TOX_PUBLIC_KEY} -lt 30 ]; then
        echo $'WARNING: Could not obtain the tox node public key' >> $INSTALL_LOG
        exit 46362
    fi

    # save the public key for later reference
    echo "$TOX_PUBLIC_KEY" > $TOX_BOOTSTRAP_ID_FILE
    echo $'Configured toxcore' >> $INSTALL_LOG
}

function create_tox_user {
    # remove any existing user
    if [ -f /home/${MY_USERNAME}/.config/tox/data.tox ]; then
        rm -f /home/${MY_USERNAME}/.config/tox/data*
    fi
    if [ -d /home/${MY_USERNAME}/.config/tox/avatars ]; then
        rm -rf /home/${MY_USERNAME}/.config/tox/avatars
    fi
    if [ ! -f /home/${MY_USERNAME}/.first_boot ]; then
        touch /home/${MY_USERNAME}/.first_boot
    fi

    if [ ! -d /home/$MY_USERNAME/Desktop ]; then
        return
    fi

    toxid -u $MY_USERNAME -n data
    chown -R ${MY_USERNAME}:${MY_USERNAME} /home/${MY_USERNAME}/.config/tox

    chmod +x /home/$MY_USERNAME/Desktop/*.desktop
    chown ${MY_USERNAME}:${MY_USERNAME} /home/$MY_USERNAME/Desktop/*
    echo $'Created Tox user' >> $INSTALL_LOG
}

function show_desktop_icons {
    if [ ! -d /home/$MY_USERNAME/Desktop ]; then
        return
    fi

    echo '#!/bin/bash' > /home/$MY_USERNAME/.showhelp
    echo "pkill $BROWSER" >> /home/$MY_USERNAME/.showhelp
    echo "$BROWSER $BROWSER_OPTIONS /home/$MY_USERNAME/help/mesh.html" >> /home/$MY_USERNAME/.showhelp
    chmod +x /home/$MY_USERNAME/.showhelp
    chown $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/.showhelp

    echo '[Desktop Entry]' > /home/$MY_USERNAME/Desktop/help.desktop
    echo 'Version=1.0' >> /home/$MY_USERNAME/Desktop/help.desktop
    echo 'Name=Help' >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[el]=Βοήθεια" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[ar]=مساعدة" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[ca]=Ajuda" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[hi]=मदद" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[fr]=Aidez-moi" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[de]=Hilfe" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[es]=Ayuda" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[it]=Aiuto" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[ru]=Помогите" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Name[zh]=帮帮我" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo 'Type=Application' >> /home/$MY_USERNAME/Desktop/help.desktop
    echo 'Comment=Show help' >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[el]=Εμφάνιση βοήθειας" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[ar]=عرض المساعدة" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[ca]=Mostra ajuda" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[hi]=मदद दिखायें" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[fr]=Afficher l'aide" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[de]=Zeig Hilfe" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[es]=Mostrar ayuda" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[it]=Mostra aiuto" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[ru]=Показать справку" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Comment[zh]=显示帮助" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Exec=bash -c /home/$MY_USERNAME/.showhelp" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo "Icon=/usr/share/${PROJECT_NAME}/avatars/icon_help.png" >> /home/$MY_USERNAME/Desktop/help.desktop
    echo 'Terminal=false' >> /home/$MY_USERNAME/Desktop/help.desktop
    echo 'Categories=Application;' >> /home/$MY_USERNAME/Desktop/help.desktop

    echo '[Desktop Entry]' > /home/$MY_USERNAME/Desktop/wifi.desktop
    echo 'Version=1.0' >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo 'Name=Wifi' >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[el]=Wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[ar]=واي فاي" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[ca]=Wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[hi]=वाई - फाई" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[fr]=Wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[de]=W-lan" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[es]=Wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[it]=Wi-Fi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[ru]=вай-фай" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Name[zh]=无线上网" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo 'Type=Application' >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo 'Comment=Check wifi status' >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[el]=Ελέγξτε την κατάσταση wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[ar]=التحقق من حالة واي فاي" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[ca]=Comprova l'estat de wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[hi]=वाईफ़ाई स्थिति की जांच करें" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[fr]=Vérifier l'état du wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[de]=WLAN-Status überprüfen" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[es]=Verificar el estado del wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[it]=Controllare lo stato wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[ru]=Проверить статус wifi" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Comment[zh]=检查wifi状态" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo 'Exec=mate-terminal --full-screen -e "sudo batman monitor"' >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo "Icon=/usr/share/${PROJECT_NAME}/avatars/icon_wifi.png" >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo 'Terminal=false' >> /home/$MY_USERNAME/Desktop/wifi.desktop
    echo 'Categories=Application;' >> /home/$MY_USERNAME/Desktop/wifi.desktop

    echo '[Desktop Entry]' > /home/$MY_USERNAME/Desktop/restart.desktop
    echo 'Version=1.0' >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo 'Name=Network Restart' >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[el]=Δικτυακή επανεκκίνηση" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[ar]=إعادة تشغيل الشبكة" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[ca]=Reinicia la xarxa" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[hi]=नेटवर्क पुनरारंभ करें" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[fr]=Redémarrage du réseau" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[de]=Netzwerk Neustart" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[es]=Reinicio de red" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[it]=Riavvia rete" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[ru]=Перезапуск сети" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Name[zh]=网络重新启动" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo 'Type=Application' >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo 'Comment=Restart the mesh network daemon' >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[el]=Κάντε επανεκκίνηση του δαίμονα του δικτύου ματιών" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[ar]=إعادة تشغيل شبكة شبكة الخفي" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[ca]=Reinicia el dimoni de la xarxa de malla" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[hi]=जाल नेटवर्क डेमॉन को पुनरारंभ करें" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[fr]=Redémarrez le démon réseau maillé" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[de]=Starten Sie den Mesh-Netzwerk-Daemon neu." >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[es]=Reinicie el daemon de red de malla" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[it]=Riavviare il daemon della rete mesh" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[ru]=Перезапустить демон сетчатой сети" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Comment[zh]=重新启动网状网络守护程序" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo 'Exec=mate-terminal -e "sudo batman restart 2> /dev/null"' >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo "Icon=/usr/share/${PROJECT_NAME}/avatars/icon_restart_network.png" >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo 'Terminal=false' >> /home/$MY_USERNAME/Desktop/restart.desktop
    echo 'Categories=Application;' >> /home/$MY_USERNAME/Desktop/restart.desktop

    echo '[Desktop Entry]' > /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo 'Version=1.0' >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo 'Name=New Identity' >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[el]=Νέα ταυτότητα" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[ar]=هوية جديدة" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[ca]=Nova identitat" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[hi]=नई पहचान" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[fr]=Nouvelle identité" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[de]=Neue Identität" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[es]=Nueva identidad" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[it]=Nuova Identità" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[ru]=Новая идентификация" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Name[zh]=新身份" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo 'Type=Application' >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo 'Comment=Create a new identity' >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[el]=Δημιουργήστε μια νέα ταυτότητα" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[ar]=إنشاء هوية جديدة" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[ca]=Crea una nova identitat" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[hi]=एक नई पहचान बनाएँ" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[fr]=Créer une nouvelle identité" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[de]=Erstellen Sie eine neue Identität" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[es]=Crea una nueva identidad" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[it]=Crea una nuova identità" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[ru]=Создайте новое удостоверение личности" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Comment[zh]=创建一个新的身份" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Exec=mate-terminal --full-screen -e ${PROJECT_NAME}-mesh-reset" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo "Icon=/usr/share/${PROJECT_NAME}/avatars/icon_new_identity.png" >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo 'Terminal=false' >> /home/$MY_USERNAME/Desktop/new_identity.desktop
    echo 'Categories=Application;' >> /home/$MY_USERNAME/Desktop/new_identity.desktop

    echo '[Desktop Entry]' > /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name=Social' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[el]=Κοινωνικός' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[ar]=اجتماعي' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[ca]=Social' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[hi]=सामाजिक' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[fr]=Social' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[de]=Soziale' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[es]=Social' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[it]=Sociale' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[ru]=Социальное' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Name[zh]=社会' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Type=Application' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment=A decentralized messaging and sharing app built on top of Secure Scuttlebutt" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[el]=Μια αποκεντρωμένη εφαρμογή ανταλλαγής μηνυμάτων και κοινής χρήσης που είναι ενσωματωμένη στην κορυφή του Secure Scuttlebutt" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[ar]=والرسائل اللامركزية وتبادل التطبيق بنيت على رأس سكوتليبوت الآمنة (سب)" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[ca]=Una aplicació de missatgeria i distribució descentralitzada integrada a Secure Scuttlebutt" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[hi]=सिक्योर स्कूटलबट (एसएसबी) के शीर्ष पर निर्मित एक विकेन्द्रीकृत संदेश और साझाकरण ऐप" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[fr]=Une application de messagerie et de partage décentralisée basée sur Secure Scuttlebutt" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[de]=Eine dezentralisierte Messaging- und Sharing-App, die auf Secure Scuttlebutt basiert" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[es]=Una aplicación de mensajería y uso compartido descentralizada construida sobre Secure Scuttlebutt" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[it]=Un'applicazione decentralizzata di messaggistica e condivisione costruita sulla base di Secure Shuttlebutt" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[ru]=Децентрализованное приложение для обмена сообщениями и совместного использования, построенное на основе Secure Scuttlebutt" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Comment[zh]=安全Scuttlebutt之上构建的分散式消息和共享应用程序" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Exec=bash /usr/bin/start_patchwork' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo "Icon=/usr/share/$PROJECT_NAME/avatars/icon_social.png" >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Terminal=false' >> /home/$MY_USERNAME/Desktop/social.desktop
    echo 'Categories=Application;' >> /home/$MY_USERNAME/Desktop/social.desktop

    #echo '[Desktop Entry]' > /home/$MY_USERNAME/Desktop/audio.desktop
    #echo 'Name=Audio/Music' >> /home/$MY_USERNAME/Desktop/audio.desktop
    #echo 'Type=Application' >> /home/$MY_USERNAME/Desktop/audio.desktop
    #echo 'Comment=Audio publishing and streaming' >> /home/$MY_USERNAME/Desktop/audio.desktop
    #echo 'Exec=bash /usr/bin/start_ferment' >> /home/$MY_USERNAME/Desktop/audio.desktop
    #echo "Icon=/etc/patchwork/icon_ferment.png" >> /home/$MY_USERNAME/Desktop/audio.desktop
    #echo 'Terminal=false' >> /home/$MY_USERNAME/Desktop/audio.desktop
    #echo 'Categories=Application;' >> /home/$MY_USERNAME/Desktop/audio.desktop

    # set permissions
    chmod +x /home/$MY_USERNAME/Desktop/*.desktop
    chown ${MY_USERNAME}:${MY_USERNAME} /home/$MY_USERNAME/Desktop/*
    chown ${MY_USERNAME}:${MY_USERNAME} /home/$MY_USERNAME/.config
    chown -R ${MY_USERNAME}:${MY_USERNAME} /home/$MY_USERNAME/.config/tox
    chown -R ${MY_USERNAME}:${MY_USERNAME} /home/$MY_USERNAME/.config/autostart
    chown ${MY_USERNAME}:${MY_USERNAME} /home/$MY_USERNAME/*.sh

    # link to Tahoe-LAFS Magic folder
    #ln -s /home/${MY_USERNAME}/Desktop/${TAHOELAFS_SHARED_DIR} /home/${MY_USERNAME}/${TAHOELAFS_SHARED_DIR}

    # restart caja
    killall caja
    killall mate-panel
}

function enable_batman_daemon {
    systemctl enable batman
    systemctl daemon-reload
}

function mesh_amnesic {
    if [ ! -f $MESH_AMNESIC ]; then
        return
    fi

    echo '#!/bin/bash' > /usr/bin/amnesic
    echo '' >> /usr/bin/amnesic
    echo 'MY_USERNAME=$1' >> /usr/bin/amnesic
    echo 'tomb slam all' >> /usr/bin/amnesic
    echo "if [ -f /home/${MY_USERNAME}/.bash_history ]; then" >> /usr/bin/amnesic
    echo "    shred -zu /home/${MY_USERNAME}/.bash_history" >> /usr/bin/amnesic
    echo 'fi' >> /usr/bin/amnesic
    echo "if [ -f /home/${MY_USERNAME}/.xsession-errors ]; then" >> /usr/bin/amnesic
    echo "    shred -zu /home/${MY_USERNAME}/.xsession-errors" >> /usr/bin/amnesic
    echo 'fi' >> /usr/bin/amnesic
    echo '' >> /usr/bin/amnesic
    echo 'exit 0' >> /usr/bin/amnesic
    chmod +x /usr/bin/amnesic

    if [ ! -f /etc/systemd/system/amnesic.service ]; then
        echo '[Unit]' > /etc/systemd/system/amnesic.service
        echo 'Description=Amnesic Mesh' >> /etc/systemd/system/amnesic.service
        echo '' >> /etc/systemd/system/amnesic.service
        echo '[Service]' >> /etc/systemd/system/amnesic.service
        echo 'User=root' >> /etc/systemd/system/amnesic.service
        echo 'Group=root' >> /etc/systemd/system/amnesic.service
        echo 'Type=oneshot' >> /etc/systemd/system/amnesic.service
        echo 'RemainAfterExit=true' >> /etc/systemd/system/amnesic.service
        echo 'ExecStart=/bin/true' >> /etc/systemd/system/amnesic.service
        echo "ExecStop=/usr/bin/amnesic $MY_USERNAME" >> /etc/systemd/system/amnesic.service
        echo '' >> /etc/systemd/system/amnesic.service
        echo '[Install]' >> /etc/systemd/system/amnesic.service
        echo 'WantedBy=multi-user.target' >> /etc/systemd/system/amnesic.service

        chmod +x /etc/systemd/system/amnesic.service
        systemctl daemon-reload
    fi
    systemctl enable amnesic
    systemctl start amnesic
}

function mesh_restart_daemons {
    systemctl restart avahi-daemon
    systemctl restart tox-bootstrapd
    echo $'Daemons restarted' >> $INSTALL_LOG
}

function create_tomb {
    tomb_name=$1
    tomb_size=$2

    if [ -f /tmp/${tomb_name}.tomb ]; then
        tomb slam /tmp/${tomb_name}.tomb
    fi

    # make a temporary password
    tomb dig -s ${tomb_size} /tmp/${tomb_name}.tomb
    if [ ! -f /tmp/${tomb_name}.tomb ]; then
        echo "WARNING: ${tomb_name} tomb did not install properly" >> /var/log/${PROJECT_NAME}.log
        tomb >> /var/log/${PROJECT_NAME}.log
    fi
    TOMB_TEMP_PASSWORD=$(openssl rand -base64 64 | tr -dc A-Za-z0-9 | head -c 30)

    tomb forge /mnt/ramdisk/${tomb_name}.tomb.key --tomb-pwd "${TOMB_TEMP_PASSWORD}" --unsafe
    tomb lock /tmp/${tomb_name}.tomb -k /mnt/ramdisk/${tomb_name}.tomb.key --tomb-pwd "${TOMB_TEMP_PASSWORD}" --unsafe
    tomb open /tmp/${tomb_name}.tomb -k /mnt/ramdisk/${tomb_name}.tomb.key --tomb-pwd "${TOMB_TEMP_PASSWORD}" --unsafe
    # stop stuff from popping up
    pkill caja

    # clear the temporary password
    TOMB_TEMP_PASSWORD=
}

function setup_amnesic_data {
    if [ ! -f $MESH_AMNESIC ]; then
        return
    fi
    if [ ! -d /mnt/ramdisk ]; then
        return
    fi

    # clear crypttab
    if [ -f /etc/crypttab ]; then
        shred -zu /etc/crypttab
        touch /etc/crypttab
    fi

    tomb_name=log
    create_tomb ${tomb_name} $TOMB_LOG_SIZE_MB
    if [ -d /media/${tomb_name} ]; then
        if [ -d /var/log ]; then
            if [ ! -d /var/log_base ]; then
                mv /var/log /var/log_base
            fi
        fi
        ln -s /media/${tomb_name} /var/log
        if [ -d /var/log_base ]; then
            cp -rp /var/log_base/* /media/${tomb_name}
        fi
        echo "${tomb_name} tomb created" >> $INSTALL_LOG
    else
        echo "WARNING: ${tomb_name} tomb not found" >> $INSTALL_LOG
    fi

    tomb_name=tox-bootstrapd
    if [ -f /etc/systemd/system/${tomb_name}.service ]; then
        systemctl stop ${tomb_name}
    fi
    create_tomb ${tomb_name} $TOMB_TOX_BOOTSTRAP_SIZE_MB
    if [ -d /media/${tomb_name} ]; then
        if [ -d /var/lib/tox-bootstrapd ]; then
            if [ ! -d /var/lib/tox-bootstrapd_base ]; then
                mv /var/lib/tox-bootstrapd /var/lib/tox-bootstrapd_base
            fi
        fi
        if [ -d /var/lib/tox-bootstrapd ]; then
            shred -zu /var/lib/tox-bootstrapd/*
            rm -rf /var/lib/tox-bootstrapd
        fi
        ln -s /media/${tomb_name} /var/lib/tox-bootstrapd
        if [ -d /var/lib/tox-bootstrapd_base ]; then
            cp -rp /var/lib/tox-bootstrapd_base/* /media/${tomb_name}
        fi
        echo "${tomb_name} tomb created" >> $INSTALL_LOG
    else
        echo "WARNING: ${tomb_name} tomb not found" >> $INSTALL_LOG
    fi

    tomb_name=tox
    create_tomb ${tomb_name} $TOMB_TOX_SIZE_MB
    if [ -d /media/${tomb_name} ]; then
        if [ ! -d /home/${MY_USERNAME}/.config ]; then
            mkdir -p /home/${MY_USERNAME}/.config
            chown ${MY_USERNAME}:${MY_USERNAME} /home/${MY_USERNAME}/.config
        fi
        if [ -d /home/${MY_USERNAME}/.config/${tomb_name} ]; then
            rm -rf /home/${MY_USERNAME}/.config/${tomb_name}
        fi
        ln -s /media/${tomb_name} /home/${MY_USERNAME}/.config/${tomb_name}
        chown -R ${MY_USERNAME}:${MY_USERNAME} /home/${MY_USERNAME}/.config/${tomb_name}
        chown -R ${MY_USERNAME}:${MY_USERNAME} /media/${tomb_name}
        echo "${tomb_name} tomb created" >> $INSTALL_LOG
    else
        echo "WARNING: ${tomb_name} tomb not found" >> $INSTALL_LOG
    fi
}

function setup_ipfs {
    IPFS_PATH=/usr/bin
    IPFS_KEY_LENGTH=2048
    IPFS_COMMAND=$IPFS_PATH/ipfs
    IPFS_PUBLIC=/home/$MY_USERNAME/.ipfs-public

    su -c "systemctl --user enable ipfs" - $MY_USERNAME

    if [ -f $CURRENT_BLOG_INDEX ]; then
        shred -zu $CURRENT_BLOG_INDEX
    fi

    if [ -d /home/$MY_USERNAME/Public ]; then
        rm /home/$MY_USERNAME/Desktop/Public
        rm -rf /home/$MY_USERNAME/Public
    fi

    if [ -d /home/$MY_USERNAME/CreateBlog/content/images ]; then
        shred -zu /home/$MY_USERNAME/CreateBlog/content/images/*
    fi

    if [ -d /home/$MY_USERNAME/CreateBlog/content ]; then
        shred -zu /home/$MY_USERNAME/CreateBlog/content/*
        if grep -q "THEME=" /home/$MY_USERNAME/CreateBlog/pelicanconf.py; then
            sed -i "s|THEME=.*|THEME='themes/nice-blog'|g" /home/$MY_USERNAME/CreateBlog/pelicanconf.py
        else
            echo "THEME='themes/nice-blog'" >> /home/$MY_USERNAME/CreateBlog/pelicanconf.py
        fi
    fi

    if [ -d /home/$MY_USERNAME/.ipfs ]; then
        shred -zu /home/$MY_USERNAME/.ipfs/config
        rm -rf /home/$MY_USERNAME/.ipfs
        su -c "systemctl --user restart ipfs" - $MY_USERNAME
    else
        su -c "systemctl --user start ipfs" - $MY_USERNAME
    fi

    if [ -f /home/$MY_USERNAME/.blog-index ]; then
        shred -zu /home/$MY_USERNAME/.blog-index
    fi

    if [ -f /home/$MY_USERNAME/.blog-theme-index ]; then
        shred -zu /home/$MY_USERNAME/.blog-theme-index
    fi

    if [ -f /home/$MY_USERNAME/.ipfs-id ]; then
        shred -zu /home/$MY_USERNAME/.ipfs-id
    fi

    if [ -f /home/$MY_USERNAME/.ipfs-public ]; then
        shred -zu /home/$MY_USERNAME/.ipfs-public
    fi

    su -c "$IPFS_COMMAND init -b $IPFS_KEY_LENGTH" - $MY_USERNAME
    if [ ! -d /home/$MY_USERNAME/.ipfs ]; then
        echo "IPFS could not be initialised for user $MY_USERNAME" >> $INSTALL_LOG
        return
    fi

    MY_IPFS_ID=/home/$MY_USERNAME/.ipfs-id
    su -c "echo \$($IPFS_COMMAND id | grep '\"ID\":' | awk -F '\"' '{print \$4}') > $MY_IPFS_ID" - $MY_USERNAME
    if [ ! -f $MY_IPFS_ID ]; then
        echo 'No IPFS identity was created' >> $INSTALL_LOG
        return
    fi

    IPFS_PEER_ID=$(cat $MY_IPFS_ID)
    if [ ${#IPFS_PEER_ID} -lt 10 ]; then
        echo 'Invalid IPFS peer ID' >> $INSTALL_LOG
        echo "$IPFS_PEER_ID" >> $INSTALL_LOG
        return
    fi

    # make a public directory
    TOX_ID='none'
    if [ -d /home/$MY_USERNAME/Desktop ]; then
        if [ ! -d /home/$MY_USERNAME/Public ]; then
            mkdir /home/$MY_USERNAME/Public
            echo $'Files within this directory will be publicly visible on the network' > /home/$MY_USERNAME/Public/README.txt
            chown -R $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/Public
            ln -s /home/$MY_USERNAME/Public /home/$MY_USERNAME/Desktop/Public
            su -c "echo \$($IPFS_COMMAND add -rq /home/$MY_USERNAME/Public | tail -n 1) > $IPFS_PUBLIC" - $MY_USERNAME
            if [ ! -f $IPFS_PUBLIC ]; then
                echo $'Unable to create public IPFS directory' >> $INSTALL_LOG
                exit 368225
            fi
        fi
        TOX_ID=$(su -c 'toxid' - $MY_USERNAME)
    fi

    create_avahi_mesh_service "ipfs_id" "ipfs_id" "udp" "$IPFS_PORT" "${IPFS_PEER_ID}:${TOX_ID}"

    echo "IPFS installed with ID ${IPFS_PEER_ID}" >> $INSTALL_LOG
}

function setup_tahoelafs {
    reconfigure_tahoelafs

    TAHOELAFS_CONFIG=/home/${MY_USERNAME}/.tahoe/tahoe.cfg
    if [ ! -f ${TAHOELAFS_CONFIG} ]; then
        exit 673923
    fi
    echo $'Configured Tahoe-LAFS' >> $INSTALL_LOG
}

function create_user_vpn_key {
    username=$1

    if [ ! -d /home/$username ]; then
        return
    fi

    echo $"Creating VPN key for $username" >> /var/log/${PROJECT_NAME}.log

    cd /etc/openvpn/easy-rsa

    if [ -f /etc/openvpn/easy-rsa/keys/$username.crt ]; then
        rm /etc/openvpn/easy-rsa/keys/$username.crt
    fi
    if [ -f /etc/openvpn/easy-rsa/keys/$username.key ]; then
        rm /etc/openvpn/easy-rsa/keys/$username.key
    fi
    if [ -f /etc/openvpn/easy-rsa/keys/$username.csr ]; then
        rm /etc/openvpn/easy-rsa/keys/$username.csr
    fi

    sed -i 's| --interact||g' build-key
    ./build-key "$username"

    if [ ! -f /etc/openvpn/easy-rsa/keys/$username.crt ]; then
        echo $'VPN user cert not generated' >> /var/log/${PROJECT_NAME}.log
        exit 783528
    fi
    user_cert=$(cat /etc/openvpn/easy-rsa/keys/$username.crt)
    if [ ${#user_cert} -lt 10 ]; then
        cat /etc/openvpn/easy-rsa/keys/$username.crt
        echo $'User cert generation failed' >> /var/log/${PROJECT_NAME}.log
        exit 634659
    fi
    if [ ! -f /etc/openvpn/easy-rsa/keys/$username.key ]; then
        echo $'VPN user key not generated'
        exit 682523
    fi
    user_key=$(cat /etc/openvpn/easy-rsa/keys/$username.key)
    if [ ${#user_key} -lt 10 ]; then
        cat /etc/openvpn/easy-rsa/keys/$username.key
        echo $'User key generation failed'
        exit 285838
    fi

    user_vpn_cert_file=/home/$username/$OPENVPN_KEY_FILENAME

    echo 'client' > $user_vpn_cert_file
    echo 'dev tun' >> $user_vpn_cert_file
    echo 'proto tcp' >> $user_vpn_cert_file
    echo "remote localhost $STUNNEL_PORT" >> $user_vpn_cert_file
    echo "route $DEFAULT_DOMAIN_NAME 255.255.255.255 net_gateway" >> $user_vpn_cert_file
    echo 'resolv-retry infinite' >> $user_vpn_cert_file
    echo 'nobind' >> $user_vpn_cert_file
    echo 'tun-mtu 1500' >> $user_vpn_cert_file
    echo 'tun-mtu-extra 32' >> $user_vpn_cert_file
    echo 'mssfix 1450' >> $user_vpn_cert_file
    echo 'persist-key' >> $user_vpn_cert_file
    echo 'persist-tun' >> $user_vpn_cert_file
    echo 'auth-nocache' >> $user_vpn_cert_file
    echo 'remote-cert-tls server' >> $user_vpn_cert_file
    echo 'comp-lzo' >> $user_vpn_cert_file
    echo 'verb 3' >> $user_vpn_cert_file
    echo '' >> $user_vpn_cert_file

    echo '<ca>' >> $user_vpn_cert_file
    cat /etc/openvpn/ca.crt >> $user_vpn_cert_file
    echo '</ca>' >> $user_vpn_cert_file

    echo '<cert>' >> $user_vpn_cert_file
    cat /etc/openvpn/easy-rsa/keys/$username.crt >> $user_vpn_cert_file
    echo '</cert>' >> $user_vpn_cert_file

    echo '<key>' >> $user_vpn_cert_file
    cat /etc/openvpn/easy-rsa/keys/$username.key >> $user_vpn_cert_file
    echo '</key>' >> $user_vpn_cert_file

    chown $username:$username $user_vpn_cert_file

    # keep a backup
    cp $user_vpn_cert_file /etc/openvpn/easy-rsa/keys/$username.ovpn

    #rm /etc/openvpn/easy-rsa/keys/$username.crt
    #rm /etc/openvpn/easy-rsa/keys/$username.csr
    shred -zu /etc/openvpn/easy-rsa/keys/$username.key

    echo $"VPN key created at $user_vpn_cert_file" >> /var/log/${PROJECT_NAME}.log
}

function vpn_generate_keys {
    # generate host keys
    if [ ! -f /etc/openvpn/dh2048.pem ]; then
        ${PROJECT_NAME}-dhparam -o /etc/openvpn/dh2048.pem
    fi
    if [ ! -f /etc/openvpn/dh2048.pem ]; then
        echo $'vpn dhparams were not generated' >> /var/log/${PROJECT_NAME}.log
        exit 73724523
    fi
    cp /etc/openvpn/dh2048.pem /etc/openvpn/easy-rsa/keys/dh2048.pem

    cd /etc/openvpn/easy-rsa
    . ./vars
    ./clean-all
    vpn_openssl_version='1.0.0'
    if [ ! -f openssl-${vpn_openssl_version}.cnf ]; then
        echo $"openssl-${vpn_openssl_version}.cnf was not found" >> /var/log/${PROJECT_NAME}.log
        exit 7392353
    fi
    cp openssl-${vpn_openssl_version}.cnf openssl.cnf

    if [ -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt ]; then
        rm /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt
    fi
    if [ -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.key ]; then
        rm /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.key
    fi
    if [ -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.csr ]; then
        rm /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.csr
    fi
    sed -i 's| --interact||g' build-key-server
    sed -i 's| --interact||g' build-ca
    ./build-ca
    ./build-key-server ${OPENVPN_SERVER_NAME}
    if [ ! -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt ]; then
        echo $'OpenVPN crt not found' >> /var/log/${PROJECT_NAME}.log
        exit 7823352
    fi
    server_cert=$(cat /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt)
    if [ ${#server_cert} -lt 10 ]; then
        cat /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.crt
        echo $'Server cert generation failed' >> /var/log/${PROJECT_NAME}.log
        exit 3284682
    fi

    if [ ! -f /etc/openvpn/easy-rsa/keys/${OPENVPN_SERVER_NAME}.key ]; then
        echo $'OpenVPN key not found' >> /var/log/${PROJECT_NAME}.log
        exit 6839436
    fi
    if [ ! -f /etc/openvpn/easy-rsa/keys/ca.key ]; then
        echo $'OpenVPN ca not found' >> /var/log/${PROJECT_NAME}.log
        exit 7935203
    fi
    cp /etc/openvpn/easy-rsa/keys/{$OPENVPN_SERVER_NAME.crt,$OPENVPN_SERVER_NAME.key,ca.crt} /etc/openvpn

    create_user_vpn_key ${MY_USERNAME}
}

function generate_stunnel_keys {
    echo "Creating stunnel keys" >> /var/log/${PROJECT_NAME}.log
    openssl req -x509 -nodes -days 3650 -sha256 \
            -subj "/O=$VPN_ORGANISATION/OU=$VPN_UNIT/C=$VPN_COUNTRY_CODE/ST=$VPN_AREA/L=$VPN_LOCATION/CN=$HOSTNAME" \
            -newkey rsa:2048 -keyout /etc/stunnel/key.pem \
            -out /etc/stunnel/cert.pem
    if [ ! -f /etc/stunnel/key.pem ]; then
        echo $'stunnel key not created' >> /var/log/${PROJECT_NAME}.log
        exit 793530
    fi
    if [ ! -f /etc/stunnel/cert.pem ]; then
        echo $'stunnel cert not created' >> /var/log/${PROJECT_NAME}.log
        exit 204587
    fi
    chmod 400 /etc/stunnel/key.pem
    chmod 640 /etc/stunnel/cert.pem

    cat /etc/stunnel/key.pem /etc/stunnel/cert.pem >> /etc/stunnel/stunnel.pem
    chmod 640 /etc/stunnel/stunnel.pem

    openssl pkcs12 -export -out /etc/stunnel/stunnel.p12 -inkey /etc/stunnel/key.pem -in /etc/stunnel/cert.pem -passout pass:
    if [ ! -f /etc/stunnel/stunnel.p12 ]; then
        echo $'stunnel pkcs12 not created' >> /var/log/${PROJECT_NAME}.log
        exit 639353
    fi
    chmod 640 /etc/stunnel/stunnel.p12

    cp /etc/stunnel/stunnel.pem /home/$MY_USERNAME/stunnel.pem
    cp /etc/stunnel/stunnel.p12 /home/$MY_USERNAME/stunnel.p12
    chown $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/stunnel*
    echo "stunnel keys created" >> /var/log/${PROJECT_NAME}.log
}

function mesh_setup_vpn {
    vpn_generate_keys

    cp /etc/stunnel/stunnel-client.conf /home/$MY_USERNAME/stunnel-client.conf
    chown $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/stunnel*

    generate_stunnel_keys

    sed -i 's|tun-mtu .*|tun-mtu 1532|g' /home/$MY_USERNAME/client.ovpn
    chown $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/client.ovpn
    chown $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/stunnel*

    # create an archive of the vpn client files
    cd /home/$MY_USERNAME
    tar -czvf vpn.tar.gz stunnel* client.ovpn
    chown $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/vpn.tar.gz

    systemctl restart openvpn
}

function initialise_scuttlebot_pub {
    chown -R scuttlebot:scuttlebot /etc/scuttlebot

    systemctl enable scuttlebot.service
    systemctl daemon-reload
    systemctl start scuttlebot.service

    sleep 3

    if [ ! -d /etc/scuttlebot/.ssb ]; then
        echo $'Scuttlebot config not generated' >> /var/log/${PROJECT_NAME}.log
        exit 73528
    fi

    echo '{' > /etc/scuttlebot/.ssb/config
    echo "  \"host\": \"${HOSTNAME}\"," >> /etc/scuttlebot/.ssb/config
    echo "  \"port\": ${SCUTTLEBOT_PORT}," >> /etc/scuttlebot/.ssb/config
    echo '  "allowPrivate": true,' >> /etc/scuttlebot/.ssb/config
    echo '  "timeout": 30000,' >> /etc/scuttlebot/.ssb/config
    echo '  "pub": true,' >> /etc/scuttlebot/.ssb/config
    echo '  "local": true,' >> /etc/scuttlebot/.ssb/config
    echo '  "friends": {' >> /etc/scuttlebot/.ssb/config
    echo '    "dunbar": 150,' >> /etc/scuttlebot/.ssb/config
    echo '    "hops": 3' >> /etc/scuttlebot/.ssb/config
    echo '  },' >> /etc/scuttlebot/.ssb/config
    echo '  "gossip": {' >> /etc/scuttlebot/.ssb/config
    echo '    "connections": 2' >> /etc/scuttlebot/.ssb/config
    echo '  },' >> /etc/scuttlebot/.ssb/config
    echo '  "master": [],' >> /etc/scuttlebot/.ssb/config
    echo '  "logging": {' >> /etc/scuttlebot/.ssb/config
    echo '    "level": "error"' >> /etc/scuttlebot/.ssb/config
    echo '  }' >> /etc/scuttlebot/.ssb/config
    echo '}' >> /etc/scuttlebot/.ssb/config
    chown scuttlebot:scuttlebot /etc/scuttlebot/.ssb/config
    systemctl restart scuttlebot.service
}

# whether to reset the identity
set_new_identity=
if [ $2 ]; then
    if [[ "$2" == $"new"* ]]; then
        if [ ! -f $MESH_INSTALL_SETUP ]; then
            touch $MESH_INSTALL_SETUP
        fi
        set_new_identity=1
    fi
    if [[ "$2" == $"amnesic"* ]]; then
        if [ ! -f $MESH_AMNESIC ]; then
            touch $MESH_AMNESIC
        fi
        if [ ! -f $MESH_INSTALL_SETUP ]; then
            touch $MESH_INSTALL_SETUP
        fi
        set_new_identity=1
    fi
fi

if [ -f $MESH_INSTALL_SETUP ]; then
    if [ $1 ]; then
        MY_USERNAME=$1
    fi

    if [ ! $set_new_identity ]; then
        # sleep in order to allow other daemons to start up
        sleep 5
    fi

    # clear the install log
    if [ -f $INSTALL_LOG ]; then
        rm $INSTALL_LOG
    fi

    # Remove SSB/Patchwork files
    if [ -d /home/$MY_USERNAME/.ssb ]; then
        rm -rf /home/$MY_USERNAME/.ssb
    fi

    # Remove vpn host keys
    if [ -d /etc/openvpn/easy-rsa/keys ]; then
        rm -rf /etc/openvpn/easy-rsa/keys/*
    fi

    # Remove hidden service
    if [ -d /var/lib/tor/hidden_service_mesh ]; then
        rm -rf /var/lib/tor/hidden_service_mesh
    fi

    # Remove any existing vpn client keys
    if [ -f /home/$MY_USERNAME/vpn.tar.gz ]; then
        rm /home/$MY_USERNAME/vpn.tar.gz
    fi
    if [ -f /home/$USERNAME/stunnel.pem ]; then
        rm /home/$USERNAME/stunnel.pem
    fi
    if [ -f /home/$USERNAME/stunnel.p12 ]; then
        rm /home/$USERNAME/stunnel.p12
    fi

    # Remove cryptpad datastore
    if [ -d $CRYPTPAD_DIR/datastore ]; then
        rm -rf $CRYPTPAD_DIR/datastore
    fi

    echo $'Beginning mesh node setup' >> $INSTALL_LOG

    if [ -d /home/$MY_USERNAME/.config ]; then
        chown ${MY_USERNAME}:${MY_USERNAME} /home/$MY_USERNAME/.config
    fi

    systemctl stop tor
    systemctl disable tor
    echo $'TOR disabled' >> $INSTALL_LOG

    #tomb slam all
    tmp_ram_disk 100
    enable_predictable_device_names
    enable_batman_daemon
    #create_ram_disk 1
    #setup_amnesic_data
    change_avahi_name
    if [ -d $CRYPTPAD_DIR ]; then
        systemctl start cryptpad
    fi
    configure_toxcore
    create_tox_user
    #setup_tahoelafs
    mesh_setup_vpn
    initialise_scuttlebot_pub
    setup_ipfs
    enable_cryptpad
    mesh_amnesic
    make_root_read_only

    if [ ! -f $MESH_AMNESIC ]; then
        rm $MESH_INSTALL_SETUP
        systemctl disable mesh-setup.service
    fi

    show_desktop_icons

    mesh_restart_daemons
    if [ ! -f $MESH_INSTALL_COMPLETED ]; then
        echo $'Mesh node setup complete' >> $INSTALL_LOG
        touch $MESH_INSTALL_COMPLETED
        if [ -d /home/$MY_USERNAME/Desktop ]; then
            touch $FIRST_BOOT
            chown ${MY_USERNAME}:${MY_USERNAME} $FIRST_BOOT
        fi

        # set the desktop background
        if [ -d /home/$MY_USERNAME/Desktop ]; then
            MESH_DESKTOP_BACKGROUND_IMAGE=/usr/local/share/${PROJECT_NAME}_mesh_background.png
            cp $MESH_DESKTOP_BACKGROUND_IMAGE /usr/share/images/desktop-base/${PROJECT_NAME}_mesh_background.png
            rm /usr/share/images/desktop-base/desktop-background
            ln -s /usr/share/images/desktop-base/${PROJECT_NAME}_mesh_background.png /usr/share/images/desktop-base/desktop-background
        fi
        if [ -f /etc/default/grub ]; then
            update-grub
        fi
        systemctl reboot -i
    fi
fi

exit 0
