#!/bin/bash

astra_http_mirror(){
  show_greetings() {
    echo " ";
    echo " Utility to launch local HTTP mirror of ALTLinux repository";
    echo " Copyright (c) 2020-2023 Alexey Kuryakin kouriakine@mail.ru";
    echo " Version: 20230205";
    echo " ";
  };
  show_title() {
    echo " ";
    echo " $*";
    echo " ";
  };
  execute(){
    echo "";
    echo "$(date +%Y.%m.%d-%H:%M:%S) - Execute: $*";
    echo "";
    $*;
  };
  skip(){
   true;
  };
  mirror_readable(){
    execute sudo chmod -cR a+r /srv/public/mirror/* 2>/dev/null;
  };
  lighttpd_install(){
    [ -e /etc/init.d/lighttpd ] || {
     execute sudo apt-get update;
     execute sudo apt-get install lighttpd;
    };
  };
  lighttpd_status(){
   execute /etc/init.d/lighttpd status;
  };
  lighttpd_restart(){
   execute sudo /etc/init.d/lighttpd restart;
   sleep $1;
  };
  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}";
  };
  links_srv_to_www(){
   local www="/var/www/html";
   local mir="$www/mirror";
   local srv="/srv/public/mirror";
   [ -L $mir ] && execute sudo rm -f $mir;
   [ -L $www ] && execute sudo rm -f $www;
   [ -d $www ] && { [ -e $www.old ] || execute sudo mv -f $www $www.old; };
   [ -d $www ] || { execute sudo mkdir -p $www; execute sudo chown root:root $www; execute sudo chmod 755 $www; }
   print_index_html | sudo tee $www/index.html;
   execute sudo ln -s -T $srv $mir;
  };
  enable_dir_listing(){
   local conf="/etc/lighttpd/lighttpd.conf";
   [ -e $conf ] && {
    [ -z "$(cat $conf | grep server.dir-listing)" ] && {
     echo -ne "\nserver.dir-listing = \"enable\"\n" | sudo tee -a $conf;
     skip lighttpd_restart;
    };
   };
  };
  clear;
  show_greetings;
  mirror_readable;
  lighttpd_install;
  links_srv_to_www;
  enable_dir_listing;
  lighttpd_restart 1;
  lighttpd_status;
  show_title "Done";
};
astra_http_mirror;
