wize.rb 6.16 KB
#!/usr/bin/env ruby

require 'optparse'

# Variables globales $version, $auteur et $date
$version = "0.1"
$auteur = "William Daniau"
$date = "2019 10 11"

# Global directory definitions
$zimShareDir = "#{ENV['HOME']}/.local/share/zim"
$zimHtmlTemplateDir = "#{$zimShareDir}/templates/html"
$zimConfigDir = "#{ENV['HOME']}/.config/zim"

# Parse arguments class
class ParseOptions
  def self.parse(args)
    options = Hash.new

    opt_parser = OptionParser.new do |opts|
      opts.banner = "\nUtilisation : wize.rb [options]"
      opts.separator ""
      whatIDo = <<-AFP

      liste ou applique une configuration de template wize pour zim

            AFP

      opts.separator whatIDo

      opts.on("-i",
              "--install",
              " - crée le fichier Wize_Print.html à partir",
              "du  fichier template correspondant en",
              "remplaçant %%HOME%% par la valeur de $HOME.",
              " - Installe un lien symbolique dans",
              "le dossier de config de zim.",
              " - Applique le thème wize de base",
              "A éxécuter a priori une seule fois .") do |l|
        options[:install] = l
      end

      opts.on("-l",
              "--list",
              "Liste les configurations disponibles") do |l|
        options[:list] = l
      end

      opts.on("-p",
              "--print",
              "Affiche la configuration actuelle") do |p|
        options[:print] = p
      end

      opts.on("-a",
              "--apply CONF",
              "applique la config CONF") do |conf|
        options[:conf] = conf
      end

      opts.separator ""
      opts.separator "       Options standard:"
      opts.on_tail("-h", "--help", "Affiche ce message") do
        puts opts
        puts ""
        exit
      end
      opts.on_tail("-v", "--version", "Affiche la version") do
        puts "Version : " + $version
        puts "Auteur : " + $auteur
        puts "Date : " + $date
        puts ""
        exit
      end
    end

    opt_parser.parse!(args)
    options
  end
end

# Get the config list
def listConfigs
  Dir.chdir($zimHtmlTemplateDir)
  a = `ls`.split(/\n/)
  names = []
  r = /^common-(.+)$/
  a.each { |f|
    if f =~ r
      names.push($1)
    end
  }
  names
end

# Get the current config by looking at print-common
def getCurrent
  Dir.chdir($zimHtmlTemplateDir)
  File.readlink("print-common") =~ /^common-(.+)$/
  $1
end

# Apply a config
def applyConfig(name)
  Dir.chdir($zimHtmlTemplateDir)
  list = ["Wize", "Wize_with_index", "Wize_with_index_sod", "Wize_S5"]
  list.each { |l|
    # Removing previous content
    system("rm -rf #{l}/common")
    system("rm -rf #{l}/common-spec")
    # Copying new content
    system("cp -r common #{l}/common")
    system("cp -r common-#{name} #{l}/common-spec")
  }
  # For print
  system("rm -f print-common")
  system("ln -s common-#{name} print-common")
end

# Is the name a valid config?
def configInList?(name, names)
  names.include? name
end

# Re-create Wize_Print.html from template
# and initialize link into zim config directory
def installWize
  Dir.chdir($zimHtmlTemplateDir)
  begin
    printTemplate = File.new("Wize_Print_Template.tpl", "r")
  rescue
    puts "cannot open print file for reading"
    exit
  end
  tabfile = []
  stor = '%%HOME%%'
  rby = ENV['HOME']
  printTemplate.readlines.each { |line|
    line.gsub!(stor,rby)
    tabfile.push(line)
  }
  printTemplate.close
  begin
    printFile = File.new("Wize_Print.html", "w")
  rescue
    puts "cannot open print file for writing"
    exit
  end
  tabfile.each { |line|
    printFile.write line
  }
  printFile.close

  Dir.chdir($zimConfigDir)
  system("rm -f style.conf")
  system("ln -s #{$zimShareDir}/style.conf style.conf")
  
  # Now apply wize theme
  applyConfig("wize")
  createStyleFile("wize")
end

# Create style-name.conf according to common-name/zim-variables.css
def createStyleFile(name)
  lfTags = ["--main-header-color",
            "--main-menu-u-decoration",
            "--main-menu-u-background-color",
            "--main-strike-color",
            "--main-tt-color",
            "--main-pre-color",
            "--main-link-color"]

  # First we load the css file and parse it
  Dir.chdir($zimHtmlTemplateDir)
  begin
    nameCSS = File.new("common-#{name}/zim-variables.css", "r")
  rescue
    puts "cannot open common-#{name}/zim-variables.css for reading"
    exit
  end
  sCSS = nameCSS.read
  regComment = /\/\*.*?\*\//m
  sCSS.gsub!(regComment, '')
  sTags = {}
  lfTags.each { |tag|
    var = Regexp.escape(tag)
    reg = /#{var}\s*:\s*(\S+)\s*;/
    sCSS =~ reg
    sTags[tag] = $1
    # On traite le cas particulier du u-decoration
    if tag == "--main-menu-u-decoration"
      sTags[tag] = sTags[tag] == 'underline' ? 'PANGO_UNDERLINE_SINGLE' : ''
    end
  }

  # know read the style template
  Dir.chdir($zimShareDir)
  begin
    styleTemplate = File.new("style-template.conf", "r")
  rescue
    puts "cannot open style-template.conf for reading"
    exit
  end
  styleTemplateString = styleTemplate.read
  lfTags.each { |tag|
    styleTemplateString.gsub!("%%#{tag}%%", sTags[tag])
  }
  # Now write the file
  begin
    styleOutput = File.new("style-#{name}.conf", "w")
  rescue
    puts "cannot open style-#{name}.conf for writing"
    exit
  end
  styleOutput.write styleTemplateString
  styleOutput.close
  # Now create the symbolic link
  system("rm style.conf")
  system("ln -s style-#{name}.conf style.conf")
end

# Parse arguments using the class and get results in a hash
options = ParseOptions.parse(ARGV)
if options.length == 0
  puts "Utiliser -h pour l'aide"
  exit
end

# get existing configs
configs = listConfigs

# Installation
if options[:install]
  installWize
  exit
end

# List
if options[:list]
  configs.each { |c|
    puts c
  }
  exit
end

# Print
if options[:print]
  puts getCurrent
  exit
end

# Apply
if options[:conf]
  conf = options[:conf]
  # is it a valid config?
  if !configInList?(conf, configs)
    puts "#{conf} n'est pas une configuration valide"
    exit
  end
  # we have a valid config
  applyConfig(conf)
  createStyleFile(conf)
  #
  puts "All done!"
  puts "Les modifications de templates html sont appliquée directement,"
  puts "mais il faut redémarrer zim pour que les modifications y aapparaissent"
end