#!/bin/bash
#
# .---.                  .              .
# |                      |              |
# |--- .--. .-.  .-.  .-.|  .-. .--.--. |.-.  .-. .--.  .-.
# |    |   (.-' (.-' (   | (   )|  |  | |   )(   )|  | (.-'
# '    '     --'  --'  -' -  -' '  '   -' -'   -' '   -  --'
#
#                    Freedom in the Cloud
#
# Pelican static blog
#
# License
# =======
#
# Copyright (C) 2014-2017 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 writer"

IN_DEFAULT_INSTALL=0
SHOW_ON_ABOUT=1

PELICAN_DOMAIN_NAME=
PELICAN_BLOG_CODE=
PELICAN_ONION_PORT=8113

PELICAN_THEMES_REPO="https://github.com/getpelican/pelican-themes"
PELICAN_PLUGINS_REPO="https://github.com/getpelican/pelican-plugins"
DEFAULT_BLOG_TITLE=$"Freedombone Blog"

PELICAN_BLOG_INSTALL_DIR=/etc/blog
PELICAN_CURRENT_BLOG_INDEX=$PELICAN_BLOG_INSTALL_DIR/.blog-index

pelican_variables=(MY_USERNAME
                   ONION_ONLY
                   PELICAN_DOMAIN_NAME
                   PELICAN_BLOG_CODE)

function logging_on_pelican {
    echo -n ''
}

function logging_off_pelican {
    echo -n ''
}

function install_pelican_website {
    if [[ $ONION_ONLY != 'no' ]]; then
        echo -n '' > /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
        return
    fi
    function_check nginx_http_redirect
    nginx_http_redirect $PELICAN_DOMAIN_NAME
    echo 'server {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    listen 443 ssl;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    listen [::]:443 ssl;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo "    root /var/www/${PELICAN_DOMAIN_NAME}/htdocs;" >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo "    server_name ${PELICAN_DOMAIN_NAME};" >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    access_log /dev/null;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo "    error_log /dev/null;" >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    index index.html;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    charset utf-8;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    function_check nginx_ssl
    nginx_ssl $PELICAN_DOMAIN_NAME
    function_check nginx_disable_sniffing
    nginx_disable_sniffing $PELICAN_DOMAIN_NAME
    echo '    add_header Strict-Transport-Security "max-age=0;";' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location / {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    function_check nginx_limits
    nginx_limits $PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    nginx_keybase ${PELICAN_DOMAIN_NAME}
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    # block these file types' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location ~* \.(tpl|md|tgz|log|out)$ {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '        deny all;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    # deny access to all dot files' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location ~ /\. {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '        deny all;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location ~ /(data|conf|bin|inc)/ {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '      deny all;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location ~ /\.ht {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '      deny  all;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '}' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME

    function_check create_site_certificate
    create_site_certificate $PELICAN_DOMAIN_NAME 'yes'
}

function install_pelican_website_onion {
    echo 'server {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo "    listen 127.0.0.1:${PELICAN_ONION_PORT} default_server;" >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo "    root /var/www/${PELICAN_DOMAIN_NAME}/htdocs;" >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo "    server_name ${PELICAN_DOMAIN_NAME};" >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    access_log /dev/null;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo "    error_log /dev/null;" >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    index index.html;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    charset utf-8;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    function_check nginx_disable_sniffing
    nginx_disable_sniffing $PELICAN_DOMAIN_NAME
    echo '    add_header Strict-Transport-Security "max-age=0;";' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location / {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    function_check nginx_limits
    nginx_limits $PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    nginx_keybase ${PELICAN_DOMAIN_NAME}
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    # block these file types' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location ~* \.(tpl|md|tgz|log|out)$ {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '        deny all;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    # deny access to all dot files' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location ~ /\. {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '        deny all;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location ~ /(data|conf|bin|inc)/ {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '      deny all;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    location ~ /\.ht {' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '      deny  all;' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '    }' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
    echo '}' >> /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
}

function pelican_editor_config {
    if [ ! -f $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican ]; then
        echo "(add-hook 'before-save-hook 'delete-trailing-whitespace)" > $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq org-support-shift-select t)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq standard-indent 4)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq-default tab-width 4)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq c-basic-offset 4)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(mouse-wheel-mode t)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq make-backup-files t)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq version-control t)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq backup-directory-alist (quote ((".*" . "~/.emacs_backups/"))))' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo "(setq default-major-mode 'text-mode)" >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo "(dolist (hook '(text-mode-hook))" >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '    (add-hook hook (lambda () (flyspell-mode 1))))' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq-default fill-column 72)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo '(setq auto-fill-mode 0)' >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo "(add-hook 'text-mode-hook 'turn-on-auto-fill)" >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
        echo "(setq-default auto-fill-function 'do-auto-fill)" >> $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican
    fi
}

function pelican_regenerate_blog {
    clear
    echo ''
    echo $'Regenerating blog...'

    cd $PELICAN_BLOG_INSTALL_DIR
    make html
    cp -r $PELICAN_BLOG_INSTALL_DIR/output/* /var/www/$PELICAN_DOMAIN_NAME/htdocs/
    chown -R www-data:www-data /var/www/$PELICAN_DOMAIN_NAME/htdocs
}

function pelican_new_blog {
    DATESTR=$(date "+%Y-%m-%d %H:%M:%S")

    if [ ! -f $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry ]; then
        echo $'Title: Blog Post Title' > $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo $"Date: ${DATESTR}" >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo $"Author: $(toxid --showuser)" >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo $'Category: default' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo $'Tags: blog, tag' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo  '' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo $'Add your text here' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo  '' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo -n $'To include an image copy it into the /etc/blog/content/images directory, ' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo $'then link to it with:' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo  '' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo $'![My image]({filename}images/myimage.jpg)' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
        echo  '' >> $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
    fi

    if [ -f /usr/bin/emacs ]; then
        emacs -q --load $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
    else
        editor $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry
    fi

    if grep -q $"Add your text here" $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry; then
        return
    fi
    if grep -q $"Blog Post Title" $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry; then
        return
    fi
    if [ ! -f $PELICAN_CURRENT_BLOG_INDEX ]; then
        echo '0' > $PELICAN_CURRENT_BLOG_INDEX
    fi

    # move to the content directory
    CURRENT_INDEX=$(cat $PELICAN_CURRENT_BLOG_INDEX)
    mv $PELICAN_BLOG_INSTALL_DIR/.new-blog-entry $BLOG_CONTENT_PATH/${CURRENT_INDEX}_post.md

    # increment the index
    CURRENT_INDEX=$((CURRENT_INDEX + 1))
    echo "$CURRENT_INDEX" > $PELICAN_CURRENT_BLOG_INDEX

    pelican_regenerate_blog
}

function pelican_edit_blog {
    if [ ! -f $PELICAN_CURRENT_BLOG_INDEX ]; then
        return
    fi
    CURRENT_INDEX=$(cat $PELICAN_CURRENT_BLOG_INDEX)
    PREVIOUS_INDEX=$((CURRENT_INDEX - 1))
    LAST_BLOG_ENTRY=$BLOG_CONTENT_PATH/${PREVIOUS_INDEX}_post.md
    if [ ! -f $LAST_BLOG_ENTRY ]; then
        return
    fi

    if [ -f /usr/bin/emacs ]; then
        emacs -q --load $PELICAN_BLOG_INSTALL_DIR/.emacs-pelican $LAST_BLOG_ENTRY
    else
        editor $LAST_BLOG_ENTRY
    fi

    pelican_regenerate_blog
}

function pelican_delete_blog {
    if [ ! -f $PELICAN_CURRENT_BLOG_INDEX ]; then
        return
    fi
    CURRENT_INDEX=$(cat $PELICAN_CURRENT_BLOG_INDEX)
    PREVIOUS_INDEX=$((CURRENT_INDEX - 1))
    LAST_BLOG_ENTRY=$BLOG_CONTENT_PATH/${PREVIOUS_INDEX}_post.md
    if [ ! -f $LAST_BLOG_ENTRY ]; then
        return
    fi

    dialog --title $"Delete the previous blog entry" \
           --backtitle $"Freedombone Mesh" \
           --defaultno \
           --yesno $"\nAre you sure that you wish to delete the previous blog entry?" 8 60
    sel=$?
    case $sel in
        0) rm $LAST_BLOG_ENTRY
           if [ $CURRENT_INDEX -gt 0 ]; then
               CURRENT_INDEX=$PREVIOUS_INDEX
               echo "$CURRENT_INDEX" > $PELICAN_CURRENT_BLOG_INDEX
           else
               rm -f $PELICAN_CURRENT_BLOG_INDEX
           fi
           pelican_regenerate_blog
           ;;
    esac
}

function pelican_remove_bad_blog_links {
    current_theme=$1
    if [ -f $PELICAN_BLOG_INSTALL_DIR/themes/$current_theme/static/css/style.css ]; then
        sed -i '/googleapi/d' $PELICAN_BLOG_INSTALL_DIR/themes/$current_theme/static/css/style.css
    fi
}

function pelican_change_theme {
    THEMES=()
    for d in $PELICAN_BLOG_INSTALL_DIR/themes/*/ ; do
        THEME_NAME=$(echo "$d" | awk -F '/' '{print $6}')
        THEMES+=("$THEME_NAME")
    done

    themelist=""
    n=1
    theme_index=0
    curr_theme_index=
    if [ -f $PELICAN_BLOG_INSTALL_DIR/.blog-theme-index ]; then
        curr_theme_index=$(cat $PELICAN_BLOG_INSTALL_DIR/.blog-theme-index)
    fi
    for a in "${THEMES[@]}"
    do
        is_selected='off'
        if [ $curr_theme_index ]; then
            if [ $n -eq $curr_theme_index ]; then
                is_selected='on'
            fi
        else
            if [[ "$a" == 'nice-blog' ]]; then
                is_selected='on'
            fi
        fi

        themelist="$themelist $n $a $is_selected"
        n=$[n+1]
        theme_index=$[theme_index+1]
    done

    data=$(tempfile 2>/dev/null)
    trap "rm -f $data" 0 1 2 5 15
    dialog --backtitle $"Freedombone Mesh" \
           --title $"Select Blog Theme" \
           --radiolist $'Choose:' \
           80 40 20 $themelist 2> $data
    sel=$?
    case $sel in
        1) return;;
        255) return;;
    esac
    CHOSEN_THEME_INDEX=$(cat $data)
    echo "$CHOSEN_THEME_INDEX" > $PELICAN_BLOG_INSTALL_DIR/.blog-theme-index
    CHOSEN_THEME_INDEX=$((CHOSEN_THEME_INDEX - 1))

    CHOSEN_THEME=${THEMES[$CHOSEN_THEME_INDEX]}
    pelican_remove_bad_blog_links $CHOSEN_THEME
    if grep -q "THEME=" $PELICAN_BLOG_INSTALL_DIR/pelicanconf.py; then
        sed -i "s|THEME=.*|THEME='themes/${CHOSEN_THEME}'|g" $PELICAN_BLOG_INSTALL_DIR/pelicanconf.py
    else
        echo "THEME='themes/${CHOSEN_THEME}'" >> $PELICAN_BLOG_INSTALL_DIR/pelicanconf.py
    fi
    pelican_regenerate_blog
}

function configure_interactive_pelican {
    data=$(tempfile 2>/dev/null)
    trap "rm -f $data" 0 1 2 5 15
    dialog --backtitle $"Freedombone Configuration" \
           --title $"Pelican Blogging" \
           --radiolist $"Choose an operation:" 18 50 11 \
           1 $"New blog entry" off \
           2 $"Edit the previous blog entry" off \
           3 $"Delete the previous blog entry" off \
           4 $"Change theme" off \
           5 $"Exit" off 2> $data
    sel=$?
    case $sel in
        1) return;;
        255) return;;
    esac
    case $(cat $data) in
        1) pelican_new_blog;;
        2) pelican_edit_blog;;
        3) pelican_delete_blog;;
        4) pelican_change_theme;;
        5) break;;
    esac
}

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

    if [[ $ONION_ONLY != "no" ]]; then
        PELICAN_DOMAIN_NAME='pelican.local'
    else
        PELICAN_DETAILS_COMPLETE=
        while [ ! $PELICAN_DETAILS_COMPLETE ]
        do
            data=$(tempfile 2>/dev/null)
            trap "rm -f $data" 0 1 2 5 15
            if [[ $DDNS_PROVIDER == "default@freedns.afraid.org" ]]; then
                dialog --backtitle $"Freedombone Configuration" \
                       --title $"Pelican Blog Configuration" \
                       --form $"\nPlease enter your blog details.\n\nIMPORTANT: This should be a domain name which is supported by Let's Encrypt:" 14 65 2 \
                       $"Domain:" 1 1 "$(grep 'PELICAN_DOMAIN_NAME' temp.cfg | awk -F '=' '{print $2}')" 1 25 33 40 \
                       $"Code:" 2 1 "$(grep 'PELICAN_BLOG_CODE' temp.cfg | awk -F '=' '{print $2}')" 2 25 33 255 \
                       2> $data
            else
                dialog --backtitle $"Freedombone Configuration" \
                       --title $"Pelican Blog Configuration" \
                       --form $"\nPlease enter your GNU Social details. The background image URL can be left blank.\n\nIMPORTANT: This should be a domain name which is supported by Let's Encrypt:" 14 65 2 \
                       $"Domain:" 1 1 "$(grep 'PELICAN_DOMAIN_NAME' temp.cfg | awk -F '=' '{print $2}')" 1 25 33 40 \
                       2> $data
            fi
            sel=$?
            case $sel in
                1) exit 1;;
                255) exit 1;;
            esac
            PELICAN_DOMAIN_NAME=$(cat $data | sed -n 1p)
            if [ $PELICAN_DOMAIN_NAME ]; then
                if [[ $PELICAN_DOMAIN_NAME == "$HUBZILLA_DOMAIN_NAME" ]]; then
                    PELICAN_DOMAIN_NAME=""
                fi
                TEST_DOMAIN_NAME=$PELICAN_DOMAIN_NAME
                validate_domain_name
                if [[ $TEST_DOMAIN_NAME != $PELICAN_DOMAIN_NAME ]]; then
                    PELICAN_DOMAIN_NAME=
                    dialog --title $"Domain name validation" --msgbox "$TEST_DOMAIN_NAME" 15 50
                else
                    if [[ $DDNS_PROVIDER == "default@freedns.afraid.org" ]]; then
                        PELICAN_BLOG_CODE=$(cat $data | sed -n 2p)
                        validate_freedns_code "$PELICAN_BLOG_CODE"
                        if [ ! $VALID_CODE ]; then
                            PELICAN_DOMAIN_NAME=
                        fi
                    fi
                fi
            fi
            if [ $PELICAN_DOMAIN_NAME ]; then
                PELICAN_DETAILS_COMPLETE="yes"
            fi
        done

        # save the results in the config file
        write_config_param "PELICAN_BLOG_CODE" "$PELICAN_BLOG_CODE"
    fi
    write_config_param "PELICAN_DOMAIN_NAME" "$PELICAN_DOMAIN_NAME"
    APP_INSTALLED=1
}

function reconfigure_pelican {
    echo -n ''
}

function upgrade_pelican {
    echo -n ''
}

function backup_local_pelican {
    source_directory=/etc/blog
    if [ -d $source_directory ]; then
        dest_directory=pelican
        function_check backup_directory_to_usb
        backup_directory_to_usb $source_directory $dest_directory
    fi
    source_directory=/var/www/$PELICAN_DOMAIN_NAME/htdocs
    if [ -d $source_directory ]; then
        dest_directory=pelican-site
        function_check backup_directory_to_usb
        backup_directory_to_usb $source_directory $dest_directory
    fi
}

function restore_local_pelican {
    if [ -d /etc/blog ]; then
        if [ -d $USB_MOUNT_DLNA/backup/pelican ]; then
            temp_restore_dir=/root/temppelican
            function_check restore_directory_from_usb
            restore_directory_from_usb $temp_restore_dir pelican
            if [ -d $temp_restore_dir/etc/blog ]; then
                cp -r $temp_restore_dir/etc/blog/* /etc/blog/
            else
                cp -r $temp_restore_dir/* /etc/blog/
            fi
            if [ ! "$?" = "0" ]; then
                rm -rf $temp_restore_dir
                function_check set_user_permissions
                set_user_permissions
                function_check backup_unmount_drive
                backup_unmount_drive
                exit 527942
            fi
            rm -rf $temp_restore_dir
        fi
    fi
    if [ -d /var/www/$PELICAN_DOMAIN_NAME/htdocs ]; then
        if [ -d $USB_MOUNT_DLNA/backup/pelican-site ]; then
            temp_restore_dir=/root/temppelican-site
            function_check restore_directory_from_usb
            restore_directory_from_usb $temp_restore_dir pelican-site
            if [ -d $temp_restore_dir/var/www/$PELICAN_DOMAIN_NAME/htdocs ]; then
                cp -r $temp_restore_dir/var/www/$PELICAN_DOMAIN_NAME/htdocs/* /var/www/$PELICAN_DOMAIN_NAME/htdocs/
            else
                cp -r $temp_restore_dir/* /var/www/$PELICAN_DOMAIN_NAME/htdocs/
            fi
            if [ ! "$?" = "0" ]; then
                rm -rf $temp_restore_dir
                function_check set_user_permissions
                set_user_permissions
                function_check backup_unmount_drive
                backup_unmount_drive
                exit 2946282
            fi
            rm -rf $temp_restore_dir
        fi
    fi
}

function backup_remote_pelican {
    if [ -d /etc/blog ]; then
        backup_directory_to_friend /etc/blog pelican
    fi
    if [ -d /var/www/$PELICAN_DOMAIN_NAME/htdocs ]; then
        backup_directory_to_friend /var/www/$PELICAN_DOMAIN_NAME/htdocs pelican-site
    fi
}

function restore_remote_pelican {
    if [ -d /etc/blog ]; then
        if [ -d $SERVER_DIRECTORY/backup/pelican ]; then
            temp_restore_dir=/root/temppelican
            function_check restore_directory_from_friend
            restore_directory_from_friend $temp_restore_dir pelican
            if [ -d $temp_restore_dir/etc/blog ]; then
                cp -r $temp_restore_dir/etc/blog/* /etc/blog/
            else
                cp -r $temp_restore_dir/* /etc/blog/
            fi
            if [ ! "$?" = "0" ]; then
                exit 782352
            fi
            rm -rf $temp_restore_dir
        fi
    fi
    if [ -d /var/www/$PELICAN_DOMAIN_NAME/htdocs ]; then
        if [ -d $SERVER_DIRECTORY/backup/pelican-site ]; then
            temp_restore_dir=/root/temppelican-site
            function_check restore_directory_from_friend
            restore_directory_from_friend $temp_restore_dir pelican-site
            if [ -d $temp_restore_dir/var/www/$PELICAN_DOMAIN_NAME/htdocs ]; then
                cp -r $temp_restore_dir/var/www/$PELICAN_DOMAIN_NAME/htdocs/* /var/www/$PELICAN_DOMAIN_NAME/htdocs/
            else
                cp -r $temp_restore_dir/* /var/www/$PELICAN_DOMAIN_NAME/htdocs/
            fi
            if [ ! "$?" = "0" ]; then
                exit 76382562
            fi
            rm -rf $temp_restore_dir
        fi
    fi
}

function remove_pelican {
    if [ -f /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME ]; then
        nginx_dissite pelican
        rm /etc/nginx/sites-available/$PELICAN_DOMAIN_NAME
        if [ -d /var/www/$PELICAN_DOMAIN_NAME ]; then
            rm -rf /var/www/$PELICAN_DOMAIN_NAME
        fi
        systemctl reload nginx
    fi

    pip uninstall pelican
    remove_certs $PELICAN_DOMAIN_NAME

    function_check remove_onion_service
    remove_onion_service pelican ${PELICAN_ONION_PORT}
    remove_app pelican
    systemctl restart tor
}

function create_pelican_conf {
    STATIC_BLOG_FILE=$1

    echo '#!/usr/bin/env python' > $STATIC_BLOG_FILE
    echo '# -*- coding: utf-8 -*- #' >> $STATIC_BLOG_FILE
    echo 'from __future__ import unicode_literals' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo "AUTHOR=u\"$MY_USERNAME\"" >> $STATIC_BLOG_FILE
    echo "SITENAME=u'$DEFAULT_BLOG_TITLE'" >> $STATIC_BLOG_FILE
    echo "SITEURL=''" >> $STATIC_BLOG_FILE
    echo "PATH='content'" >> $STATIC_BLOG_FILE
    echo 'TIMEZONE=u"Europe/London"' >> $STATIC_BLOG_FILE
    echo "DEFAULT_LANG=u'en'" >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'FEED_ALL_ATOM=None' >> $STATIC_BLOG_FILE
    echo 'CATEGORY_FEED_ATOM=None' >> $STATIC_BLOG_FILE
    echo 'TRANSLATION_FEED_ATOM=None' >> $STATIC_BLOG_FILE
    echo 'AUTHOR_FEED_ATOM=None' >> $STATIC_BLOG_FILE
    echo 'AUTHOR_FEED_RSS=None' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'DEFAULT_PAGINATION=False' >> $STATIC_BLOG_FILE
    echo 'RELATIVE_URLS=True' >> $STATIC_BLOG_FILE
    echo "THEME='themes/nice-blog'" >> $STATIC_BLOG_FILE
}

function create_pelican_makefile {
    STATIC_BLOG_FILE=$1

    echo 'PY?=python' > $STATIC_BLOG_FILE
    echo 'PELICAN?=pelican' >> $STATIC_BLOG_FILE
    echo 'PELICANOPTS=' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'BASEDIR=$(CURDIR)' >> $STATIC_BLOG_FILE
    echo 'INPUTDIR=$(BASEDIR)/content' >> $STATIC_BLOG_FILE
    echo "OUTPUTDIR=$PELICAN_BLOG_PATH" >> $STATIC_BLOG_FILE
    echo 'CONFFILE=$(BASEDIR)/pelicanconf.py' >> $STATIC_BLOG_FILE
    echo 'PUBLISHCONF=$(BASEDIR)/publishconf.py' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'DEBUG ?= 0' >> $STATIC_BLOG_FILE
    echo 'ifeq ($(DEBUG), 1)' >> $STATIC_BLOG_FILE
    echo -e '\tPELICANOPTS += -D' >> $STATIC_BLOG_FILE
    echo 'endif' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'RELATIVE ?= 0' >> $STATIC_BLOG_FILE
    echo 'ifeq ($(RELATIVE), 1)' >> $STATIC_BLOG_FILE
    echo -e '\tPELICANOPTS += --relative-urls' >> $STATIC_BLOG_FILE
    echo 'endif' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'html:' >> $STATIC_BLOG_FILE
    echo -e '\t$(PELICAN) $(INPUTDIR) -o $(OUTPUTDIR) -s $(CONFFILE) $(PELICANOPTS)' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'clean:' >> $STATIC_BLOG_FILE
    echo -e '\t[ ! -d $(OUTPUTDIR) ] || rm -rf $(OUTPUTDIR)' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'regenerate:' >> $STATIC_BLOG_FILE
    echo -e '\t$(PELICAN) -r $(INPUTDIR) -o $(OUTPUTDIR) -s $(CONFFILE) $(PELICANOPTS)' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'serve:' >> $STATIC_BLOG_FILE
    echo 'ifdef PORT' >> $STATIC_BLOG_FILE
    echo -e '\tcd $(OUTPUTDIR) && $(PY) -m pelican.server $(PORT)' >> $STATIC_BLOG_FILE
    echo 'else' >> $STATIC_BLOG_FILE
    echo -e '\tcd $(OUTPUTDIR) && $(PY) -m pelican.server' >> $STATIC_BLOG_FILE
    echo 'endif' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'serve-global:' >> $STATIC_BLOG_FILE
    echo 'ifdef SERVER' >> $STATIC_BLOG_FILE
    echo -e '\tcd $(OUTPUTDIR) && $(PY) -m pelican.server 80 $(SERVER)' >> $STATIC_BLOG_FILE
    echo 'else' >> $STATIC_BLOG_FILE
    echo -e '\tcd $(OUTPUTDIR) && $(PY) -m pelican.server 80 0.0.0.0' >> $STATIC_BLOG_FILE
    echo 'endif' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'devserver:' >> $STATIC_BLOG_FILE
    echo 'ifdef PORT' >> $STATIC_BLOG_FILE
    echo -e '\t$(BASEDIR)/develop_server.sh restart $(PORT)' >> $STATIC_BLOG_FILE
    echo 'else' >> $STATIC_BLOG_FILE
    echo -e '\t$(BASEDIR)/develop_server.sh restart' >> $STATIC_BLOG_FILE
    echo 'endif' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'stopserver:' >> $STATIC_BLOG_FILE
    echo -e '\t$(BASEDIR)/develop_server.sh stop' >> $STATIC_BLOG_FILE
    echo -e '\t@echo "Stopped Pelican and SimpleHTTPServer processes running in background."' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'publish:' >> $STATIC_BLOG_FILE
    echo -e '\t$(PELICAN) $(INPUTDIR) -o $(OUTPUTDIR) -s $(PUBLISHCONF) $(PELICANOPTS)' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo '.PHONY: html clean regenerate serve serve-global devserver publish' >> $STATIC_BLOG_FILE
}

function create_pelican_publish_conf {
    STATIC_BLOG_FILE=$1

    echo '#!/usr/bin/env python' > $STATIC_BLOG_FILE
    echo '# -*- coding: utf-8 -*- #' >> $STATIC_BLOG_FILE
    echo 'from __future__ import unicode_literals' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'import os' >> $STATIC_BLOG_FILE
    echo 'import sys' >> $STATIC_BLOG_FILE
    echo 'sys.path.append(os.curdir)' >> $STATIC_BLOG_FILE
    echo 'from pelicanconf import *' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo "SITEURL = ''" >> $STATIC_BLOG_FILE
    echo 'RELATIVE_URLS = True' >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo "FEED_ALL_ATOM = 'feeds/all.atom.xml'" >> $STATIC_BLOG_FILE
    echo "CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml'" >> $STATIC_BLOG_FILE
    echo '' >> $STATIC_BLOG_FILE
    echo 'DELETE_OUTPUT_DIRECTORY = True' >> $STATIC_BLOG_FILE
}

function pelican_themes {
    # Clone themes separately because the themes repo sometimes has bad refs
    git clone https://github.com/KenMercusLai/BT3-Flat
    git clone https://github.com/abr4xas/Casper2Pelican
    git clone https://github.com/alexandrevicenzi/Flex
    git clone https://github.com/allenskd/Nuja
    git clone https://github.com/ir193/Responsive-Pelican
    git clone https://github.com/nairobilug/pelican-alchemy
    git clone https://github.com/livibetter-backup/apricot
    git clone https://github.com/jody-frankowski/blue-penguin
    git clone https://github.com/gregseth/pelican-bgh
    git clone https://github.com/blueicefield/pelican-blueidea
    git clone https://github.com/demianbrecht/pelican-bold
    git clone https://github.com/fly/burrito
    git clone https://github.com/yuex/pelican-iliork
    git clone https://github.com/tbunnyman/pelican-chunk
    git clone https://github.com/hdra/Pelican-Cid
    git clone https://github.com/gilsondev/pelican-clean-blog
    git clone https://github.com/porterjamesj/crowsfoot
    git clone https://github.com/22decembre/dev-random3.git
    git clone https://github.com/kura/eevee
    git clone https://github.com/talha131/pelican-elegant.git
    git clone https://github.com/callmefish/pelican-free-agent
    git clone https://github.com/jsliang/pelican-fresh
    git clone https://github.com/vaiski/genus
    git clone https://github.com/PierrePaul/html5-dopetrope
    git clone https://github.com/jvanz/pelican-hyde
    git clone https://github.com/erfaan/pelican-theme-irfan
    git clone https://github.com/slok/iris
    git clone https://github.com/badele/pelican-theme-jesuislibre
    git clone https://github.com/mothsART/pelican-lab
    git clone https://github.com/siovene/lannisport
    git clone https://github.com/lazycoder-ru/lazystrap
    git clone https://github.com/chdoig/pelican-bootstrap3-lovers
    git clone https://github.com/kplaube/maggner-pelican
    git clone https://github.com/cpaulik/martin-pelican
    git clone https://github.com/greizgh/pelican-material
    git clone https://github.com/eswarm/materialistic-pelican
    git clone https://github.com/cprieto/pelican-mediumfox
    git clone https://github.com/onuraslan/medius
    git clone https://github.com/lucachr/pelican-mg
    git clone https://github.com/BYK/pelican-neat
    git clone https://github.com/molivier/nest
    git clone https://github.com/guilherme-toti/nice-blog
    git clone https://github.com/gunchu/nikhil-theme
    git clone https://github.com/wilbur-ma/niu-x2
    git clone https://github.com/duilio/pelican-octopress-theme
    git clone https://github.com/Parbhat/pelican-blue
    git clone https://github.com/hdra/pelican-cait
    git clone https://github.com/laughk/pelican-hss
    git clone https://github.com/wrl/pelican-mockingbird
    git clone https://github.com/fle/pelican-simplegrey
    git clone https://github.com/fle/pelican-sober
    git clone https://github.com/ingwinlu/pelican-twitchy
    git clone https://github.com/badele/pelicanthemes-generator
    git clone https://github.com/jjimenezlopez/pelipress
    git clone https://github.com/xm3ron/pjport
    git clone https://github.com/kdeldycke/plumage
    git clone https://github.com/habibillah/pujangga
    git clone https://github.com/danclaudiupop/pure
    git clone https://github.com/wamonite/relapse
    git clone https://github.com/ellisonleao/pelican-semantic-ui
    git clone https://github.com/kdheepak89/pelican-smoothie
    git clone https://github.com/if1live/pelican-sora
    git clone https://github.com/redVi/storm
    git clone https://github.com/keningle/pelican-sundown
    git clone https://github.com/giulivo/pelican-svbhack
    git clone https://github.com/wting/pelican-svbtle
    git clone https://github.com/frankV/twenty-pelican-html5up
    git clone https://github.com/robulouski/voidy-bootstrap
    git clone https://github.com/samael500/w3-personal-blog
    git clone https://github.com/jarv/water-iris
    git clone https://github.com/kplaube/yapeme

    # remove any dubious css
    for d in */ ; do
        THEME_NAME=$(echo "$d" | awk -F '/' '{print $1}')
        if [ -d $d/static/css/style.css ]; then
            sed -i '/googleapi/d' $d/static/css/style.css
        fi
    done
}

function mesh_install_pelican {
    if [[ $VARIANT != "meshclient" && $VARIANT != "meshusb" && $VARIANT != "usb" ]]; then
        return
    fi

    chroot "$rootdir" apt-get -yq install python-pip
    chroot "$rootdir" pip install ipython
    chroot "$rootdir" pip install Markdown
    chroot "$rootdir" pip install typogrify
    chroot "$rootdir" pip install pelican

    PELICAN_BLOG_INSTALL_DIR=/home/$MY_USERNAME/CreateBlog
    PELICAN_BLOG_PATH=/home/$MY_USERNAME/Public/Blog

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

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

    if [ ! -d $rootdir$PELICAN_BLOG_INSTALL_DIR/content/images ]; then
        mkdir -p $rootdir$PELICAN_BLOG_INSTALL_DIR/content/images
    fi

    create_pelican_conf $rootdir$PELICAN_BLOG_INSTALL_DIR/pelicanconf.py
    create_pelican_makefile $rootdir$PELICAN_BLOG_INSTALL_DIR/Makefile
    create_pelican_publish_conf $rootdir$PELICAN_BLOG_INSTALL_DIR/publishconf.py

    mkdir -p $rootdir$PELICAN_BLOG_INSTALL_DIR/themes
    cd $rootdir$PELICAN_BLOG_INSTALL_DIR/themes
    pelican_themes

    #git clone --recursive $PELICAN_PLUGINS_REPO $rootdir$PELICAN_BLOG_INSTALL_DIR/plugins

    chroot "$rootdir" chown -R $MY_USERNAME:$MY_USERNAME $PELICAN_BLOG_INSTALL_DIR
    chroot "$rootdir" chown -R $MY_USERNAME:$MY_USERNAME /home/$MY_USERNAME/Public
}

function install_pelican {
    if [ $INSTALLING_MESH ]; then
        mesh_install_pelican
        return
    fi

    apt-get -yq install python-pip
    pip install ipython
    pip install Markdown
    pip install typogrify
    pip install pelican

    PELICAN_BLOG_PATH=/var/www/$PELICAN_DOMAIN_NAME/htdocs

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

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

    if [ ! -d $PELICAN_BLOG_INSTALL_DIR/content ]; then
        mkdir -p $PELICAN_BLOG_INSTALL_DIR/content
    fi

    create_pelican_conf $PELICAN_BLOG_INSTALL_DIR/pelicanconf.py
    create_pelican_makefile $PELICAN_BLOG_INSTALL_DIR/Makefile
    create_pelican_publish_conf $PELICAN_BLOG_INSTALL_DIR/publishconf.py

    mkdir -p $PELICAN_THEMES_REPO $PELICAN_BLOG_INSTALL_DIR/themes
    cd $PELICAN_THEMES_REPO $PELICAN_BLOG_INSTALL_DIR/themes
    pelican_themes

    #git clone --recursive $PELICAN_PLUGINS_REPO $PELICAN_BLOG_INSTALL_DIR/plugins

    chown -R $MY_USERNAME:$MY_USERNAME $PELICAN_BLOG_INSTALL_DIR
    chown -R www-data:www-data $PELICAN_BLOG_PATH

    pelican_editor_config

    PELICAN_ONION_HOSTNAME=$(add_onion_service pelican 80 ${PELICAN_ONION_PORT})
    set_completion_param "pelican onion domain" "$PELICAN_ONION_HOSTNAME"

    install_pelican_website
    install_pelican_website_onion

    pelican_regenerate_blog
    if [ ! -d $PELICAN_BLOG_INSTALL_DIR/output ]; then
        echo $'Failed to generate pelican blog'
        exit 521892
    fi

    function_check nginx_ensite
    nginx_ensite $PELICAN_DOMAIN_NAME
    systemctl restart nginx

    APP_INSTALLED=1
}

# NOTE: deliberately no exit 0
