#!/bin/bash

function ssh_mount_simply()(
  function show_greetings(){
    echo " ";
    echo " Utility to mount simply repository as sshfs.";
    echo " Copyright (c) 2023 Alexey Kuryakin kouriakine@mail.ru";
    echo " Version: 20230126";
    echo " ";
    echo "Hello, $(whoami).";
    echo "Detected $(lsb_release -is).";
    echo " ";
  };
  function show_title(){
    echo " ";
    echo " $*";
    echo " ";
  };
  function init_variables(){
    umount="0";
    for arg in $*; do if [ "$arg" = "-u" ]; then umount="1"; fi; done;
    for arg in $*; do if [ "$arg" = "--umount" ]; then umount="1"; fi; done;
  };
  function install_sshfs(){
    if [ -z "$(which sshfs)" ]; then sudo aptitude install sshfs; fi;
    if [ -n "$(which sshfs)" ]; then echo "OK, sshfs installed"; fi;
  };
  function skip(){
    return;
  };
  function call(){
   $*;
  };
  function execute(){
    echo "$*";
    call  $* ;
  };
  function do_ssh_mount(){
    local server="$1"; shift;
    local person="$1"; shift;
    local passwd="$(echo $1 | base64 -d)"; shift;
    local rights="$1"; shift;
    local usr_id="$(id -u $1)"; shift;
    local grp_id="$(id -g $1)"; shift;
    local target="/mnt/ssh/$server";
    execute sudo mkdir -p $target;
    execute sudo chmod $rights $target;
    execute sudo chown root:root $target;
    execute sudo chown $usr_id:$grp_id $target;
    if [ -n "$(cat /etc/fuse.conf | grep '\s*#\s*user_allow_other')" ]; then
      if [ ! -e /etc/fuse.conf.origin ]; then
        sudo mv -f /etc/fuse.conf /etc/fuse.conf.origin;
        cat /etc/fuse.conf.origin | sed 's/^\s*#\s*user_allow_other/user_allow_other/' | sudo tee /etc/fuse.conf;
      fi;
    fi;
    for dir in $*; do
      execute sudo umount $target/$dir;
      if [ "$umount" == "1" ]; then continue; fi;
      execute sudo mkdir -p $target/$dir;
      execute sudo chown $usr_id:$grp_id $target/$dir;
      local mounting="sshfs $person@$server:/$dir $target/$dir/ -o uid=$usr_id,gid=$grp_id,password_stdin,allow_root";
      echo "$mounting"; 
      echo "$passwd" | $mounting;
      echo "$(ls -1 $target/$dir | wc -l)";
    done;
  };
  show_greetings;
  init_variables $*;
  install_sshfs;
  show_title "simply...";
  do_ssh_mount simply main d3d3LmNydy1kYXEucnUK 777 $USER $USER    srv/public/mirror/.;
  show_title "Done";
);
ssh_mount_simply $*;
