#!/usr/bin/env python3

import os
import sys
import shutil
import uuid
import ftplib
import urllib.request

HOST = 'blog.iiiypuk.me'
USER = 'alpopov94_blog-iiiypuk-me'
PASSWORD = sys.argv[1]

def make_zip_www():
    archive_name = str(uuid.uuid4()).replace('-', '')
    shutil.make_archive(archive_name, 'zip', './public')

    return '{0}.zip'.format(archive_name)


def upload_by_ftps(archive):
    ftp = ftplib.FTP_TLS(host=HOST, user=USER, passwd=PASSWORD)

    # ftp.delete('posts')

    if ftp.pwd() == '/':
        with open(archive, 'rb') as f:
            ftp.storbinary('STOR {0}'.format(archive), f)
            os.remove(archive)

        with open('unpack.php', 'rb') as f:
            ftp.storbinary('STOR unpack.php', f)


def get_unpack(archive):
    f = urllib.request.urlopen('https://blog.iiiypuk.me/unpack.php?f={0}'.format(archive))
    f.read()

    ftp = ftplib.FTP_TLS(host=HOST, user=USER, passwd=PASSWORD)
    ftp.delete('unpack.php')


if __name__ == '__main__':
    os.system('rm -rf ./public/ &> /dev/null') # FIXIT
    os.system('hugo &> /dev/null')
    archive = make_zip_www()    # ..
    upload_by_ftps(archive)     # ..
    get_unpack(archive)         # ..
