#!/usr/bin/python3

# Copyright Jean-Philippe Guillemin <jpguillemin@sfr.fr>. This program is free software; you can redistribute
# it and/or modify it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at your option)
# any later version. Please take a look at http://www.gnu.org/copyleft/gpl.htm

import sys
sys.path.insert(1, '/usr/lib64/syncthing/')

import os
import psutil
import time
import pystray
import signal

from PIL import Image
from pystray import Icon as tray, Menu as menu, MenuItem as item

def killclean(*args):
  tray.visible = False
  print ("You killed me :p")
  time.sleep(2)
  tray.stop()

signal.signal(signal.SIGINT, killclean)
signal.signal(signal.SIGTERM, killclean)
signal.signal(signal.SIGQUIT, killclean)


def IsRunning(process):
  for proc in psutil.process_iter():
    if process.lower() == proc.name().lower():
      return True
  return False

def ImAlreadyRunning():
  count = 0
  me = "syncthing-"
  for proc in psutil.process_iter():
    if me.lower() in proc.name().lower():
      count += 1
  if count > 1:
    print ("tray icon already running")
    return True
  return False


if IsRunning('syncthing'):
  os.system("syncthing serve --browser-only &")
  print ("syncthing already running")
else:
  os.system("syncthing serve --no-browser &")
  print("Starting syncthing")

if ImAlreadyRunning():
  exit()

image1 = Image.open("/usr/share/syncthing/syncthing-stop.png")
image2 = Image.open("/usr/share/syncthing/syncthing-run.png")


def MenuAction(tray, query):
  if str(query) == "Settings":
    os.system("syncthing serve --browser-only &")
  elif str(query) == "(re)Start":
    if IsRunning('syncthing'):
      os.system("syncthing cli operations restart")
    else:
      os.system("syncthing serve --no-browser &")
  elif str(query) == "Pause":
    os.system("syncthing cli operations shutdown")
  elif str(query) == "Exit":
    os.system("syncthing cli operations shutdown")
    tray.visible = False
    time.sleep(2)
    tray.stop()

tray = pystray.Icon("SyncThing", image1, menu=pystray.Menu(
  pystray.MenuItem("Settings", MenuAction),
  pystray.MenuItem("(re)Start", MenuAction),
  pystray.MenuItem("Pause", MenuAction),
  pystray.MenuItem("Exit", MenuAction)))

tray.SETUP_THREAD_TIMEOUT = 1.0

def loop(tray):
  tray.visible = True
  while tray.visible:
    if IsRunning('syncthing'):
      tray.icon = image2
    else:
      tray.icon = image1
    time.sleep(2)
    
tray.run(setup=loop)
