#!/bin/bash

function alse_http_mirror()(
  function show_greetings() {
    echo " ";
    echo " Utility to launch local HTTP mirror of ALTLinux repository";
    echo " Copyright (c) 2020-2025 Alexey Kuryakin kouriakine@mail.ru";
    echo " Version: 20250115";
    echo " ";
  };
  function show_title() {
    echo " ";
    echo " $*";
    echo " ";
  };
  function execute(){
    echo "";
    echo "$(date +%Y.%m.%d-%H:%M:%S) - Execute: $*";
    echo "";
    $*;
  };
  function skip(){
   true;
  };
  function mirror_readable(){
    execute sudo chmod -cR a+r /srv/public/mirror/* 2>/dev/null;
  };
  function lighttpd_install(){
    if [ -e /etc/init.d/lighttpd ]; then
     echo "Found lighttpd.";
    else
     execute sudo -n aptitude update;
     execute sudo -n aptitude install lighttpd;
    fi;
  };
  function lighttpd_status(){
   execute /etc/init.d/lighttpd status;
  };
  function lighttpd_restart(){
   execute sudo -n /etc/init.d/lighttpd restart;
   sleep $1;
  };
  function print_index_html(){
   local lt="<";
   local gt=">";
   echo "${lt}html${gt}";
   echo " ${lt}body${gt}";
   echo "  ${lt}hr${gt}${lt}h1${gt}Astra Linux ${lt}big${gt}${lt}strong${gt}${lt}a href=\"mirror/\"${gt}mirror${lt}/a${gt}${lt}/strong${gt}${lt}/big${gt} on $(hostname).${lt}/h1${gt}${lt}hr${gt}";
   echo " ${lt}/body${gt}";   
   echo "${lt}/html${gt}";
  };
  function links_srv_to_www(){
   local www="/var/www/html";
   local mir="$www/mirror";
   local srv="/srv/public/mirror";
   if [ -L $mir ]; then execute sudo rm -f $mir; fi;
   if [ -L $www ]; then execute sudo rm -f $www; fi;
   if [ -d $www ]; then if [ ! -e $www.old ]; then execute sudo mv -f $www $www.old; fi; fi;
   if [ ! -d $www ]; then execute sudo mkdir -p $www; execute sudo chown root:root $www; execute sudo chmod 755 $www; fi;
   print_index_html | sudo tee $www/index.html;
   execute sudo ln -s -T $srv $mir;
  };
  function enable_dir_listing(){
   local conf="/etc/lighttpd/lighttpd.conf";
   if [ -e $conf ]; then
    if [ -z "$(cat $conf | grep 'dir-listing.activate')" ]; then
     echo -ne "\ndir-listing.activate = \"enable\"\n" | sudo tee -a $conf;
     skip lighttpd_restart;
    fi;
   fi;
  };
  function has_group(){
   if [ -n "$(getent group | cut -d: -f1 | grep "$1")" ]; then return 0; else return 1; fi;
  };
  function enable_www_user(){
   if has_group www-data; then
    if has_group vboxsf; then sudo usermod -a -G vboxsf www-data; fi;
    if has_group users;  then sudo usermod -a -G users  www-data; fi;
    groups www-data;
   fi;
  };
  clear;
  show_greetings;
  mirror_readable;
  lighttpd_install;
  links_srv_to_www;
  enable_dir_listing;
  enable_www_user;
  lighttpd_restart 1;
  lighttpd_status;
  show_title "Done";
);
alse_http_mirror;
