#!/usr/bin/env python3
"""
This is script which uploads current photos into my web server
using webdav protocol and then ask my server-side script to
process them.
"""

import netrc,easywebdav,os,sys,datetime,glob,requests
from requests.auth import HTTPDigestAuth

host='dav.wagner.pp.ru'
path='vitus/photo'
photo_path='/home/vitus/DCIM'
form='https://www.wagner.pp.ru/wwwmake/~vitus'
def dav_connect(host,user,password):
	auth = HTTPDigestAuth(user,password)
	return easywebdav.connect(host,protocol='https',auth=auth)
(user,_,password)=netrc.netrc().authenticators(host)
dav=dav_connect(host,user,password)
today = datetime.date.today()
dayprefix=today.strftime("%m.%d-")
dav.cd(path)
dav.cd(str(today.year))
founddir=None
for subdir in dav.ls():
    if subdir.name.endswith('/'):
        name=subdir.name[:-1]
    else:
        name=subdir.name
    start=name.rfind('/')
    name=name[start+1:]
    if name.startswith(dayprefix):
        founddir=name
        break
if not founddir:
    suffix=input("Enter this photo set mnemonic:")
    founddir=dayprefix+suffix
    dav.mkdir(founddir)
dav.cd(founddir)    
os.chdir(photo_path)
files=0
for f in glob.glob("*.jpg"):
    print("Uploading %s"%f)
    dav.upload(f,f)
    os.unlink(f)
    files+=1
print("Complete")
if files > 0:
    # Regenerate indexes
    if dav.exists("index.html"):
        dav.delete("index.html")
    r=requests.post(form,auth=(user,password),data={'target':'','workdir':'photo','run':'Run make'})
    r.raise_for_status()
print("Thumbnail generation started")
