Advertisement
Guest User

Untitled

a guest
Nov 19th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 16.13 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. #=============================
  4. fileName=$(basename $0)
  5. fileSettingsName="$fileName""_settings.txt"
  6. #dirFolderSc=$(dirname $0)
  7. #echo $fileName
  8. #echo $fileSettingsName
  9. #echo $dirFolderSc
  10. dirFolderSc=$(dirname $(realpath $fileName))
  11.  
  12. cd "$dirFolderSc"
  13.  
  14. if ! [ -f "$fileSettingsName" ]; then
  15.     echo -e "\e[33;1mError: ""$fileSettingsName"" not found, but it was created with default settings"
  16.     touch "$fileSettingsName"
  17.     echo -e "language: eng\n""amountArchives: 3" > "$fileSettingsName"
  18. fi
  19. #=============================
  20.  
  21. #=============================
  22. d=$(date +%H:%M:%S_%d.%m.%y)
  23. forHelp=0
  24. lang=$(grep "language:" $fileSettingsName)
  25. amount=$(grep "amountArchives:" $fileSettingsName)
  26. if ! [[ -n "$lang" && -n "$amount" ]]; then
  27.     echo -e "\e[31;1mError in ""$fileSettingsName"": Script can not read settings from file, new ""$fileSettingsName"" created successfully"
  28.     echo -e "language: eng\n""amountArchives: 3" > "$fileSettingsName"
  29.     exit 1
  30. fi
  31. lang=${lang:10}
  32. amount=${amount:16}
  33. archiveName="backup_$d.zip"
  34. #=============================
  35.  
  36. #=============================
  37. task="-q"
  38. if [ -n "$1" ]; then
  39.     task=$1
  40. else
  41.     if [ "$lang" == "eng" ]; then
  42.         echo -e "\e[31;1mError in argument_1: Argument is undefined" && exit 1
  43.     elif [ "$lang" == "rus" ]; then
  44.         echo -e "\e[31;1mОшибка в аргумент_1: Аргумент не найден" && exit 1
  45.     fi
  46. fi
  47. #=============================
  48.  
  49. #====================================================================================================================
  50. # Archiving / Архивирование
  51. #====================================================================================================================
  52. if [[ "$task" == "-a" || "$task" == "--archive" ]]; then
  53.     #=============================
  54.     ext=""
  55.     if [ -n "$2" ]; then
  56.         ext=$2
  57.     else
  58.         if [ "$lang" == "eng" ]; then
  59.             echo -e "\e[31;1mError in argument_2: Argument is undefined" && exit 1
  60.         elif [ "$lang" == "rus" ]; then
  61.             echo -e "\e[31;1mОшибка в аргумент_2: Аргумент не найден" && exit 1
  62.         fi
  63.     fi
  64.     #=============================
  65.  
  66.     #=============================
  67.     dirFolder=$(pwd)
  68.     if [ -n "$3" ]; then
  69.         if [ -d $3 ]; then
  70.             dirFolder=$3
  71.         else
  72.             if [ "$lang" == "eng" ]; then
  73.                 echo -e "\e[31;1mError in argument_3: No such directory" && exit 1
  74.             elif [ "$lang" == "rus" ]; then
  75.                 echo -e "\e[31;1mОшибка в аргумент_3: Данная директория не существует" && exit 1
  76.             fi
  77.         fi
  78.     else
  79.         if [ "$lang" == " eng" ]; then
  80.             echo -e "\e[31;1mError in argument_3: Argument is undefined" && exit 1
  81.         elif [ $lang==rus ]; then
  82.             echo -e "\e[31;1mОшибка в аргумент_3: Аргумент не найдён" && exit 1
  83.         fi
  84.     fi
  85.     #=============================
  86.  
  87.     #=============================
  88.     dirOutput=$dirFolder
  89.     if [ -n "$4" ]; then
  90.         if ! [ -d $4 ]; then
  91.             forHelp=0
  92.             mkdir -p $4 2>/dev/null || forHelp=1
  93.             if [ "$forHelp" == "0" ]; then
  94.                 if [ "$lang" == "eng" ]; then
  95.                     echo -e "\e[33;1mError in argument_4: No such directory, but it was created"
  96.                 elif [ "$lang" == "rus" ]; then
  97.                     echo -e "\e[33;1mОшибка в аргумент_4: Данная директория не существует, но была создана"
  98.                 fi
  99.             fi
  100.             if [ "$forHelp" == "1" ]; then
  101.                 if [ "$lang" == "eng" ]; then
  102.                     echo -e "\e[31;1mError in argument_4: No such directory and it can not be created" && exit 1
  103.                 elif [ "$lang" == "rus" ]; then
  104.                     echo -e "\e[31;1mОшибка в аргумент_4: Данная директория не существует и не может быть создана" && exit 1
  105.                 fi
  106.             fi
  107.         fi
  108.         dirOutput=$4
  109.         #cd $dirOutput
  110.         #if [ -d "$dirOutput""backup_""$d""_folder" ]; then
  111.         #    if [ "$lang" == "eng" ]; then
  112.         #        echo -e "\e[33;1mError in argument_4: At this point of time the archive of this directory has been already created"
  113.         #    elif [ "$lang" == "rus" ]; then
  114.         #        echo -e "\e[33;1mОшибка в аргумент_4: В данный момент времени архив соотвествующей директории уже создан"
  115.         #    fi
  116.         #    sleep 1
  117.         #fi          
  118.     fi  
  119.     #=============================
  120.  
  121.     #=============================
  122.     amountArchivesCreate=1
  123.     if [ -n "$5" ]; then
  124.         if [ "$5" == "1" ]; then
  125.             cd $dirOutput
  126.             am=$(find . -maxdepth 1 -type d -name "backup_*_folder" | wc -l)
  127.             let "am = am + 1"
  128.             #echo am="$am"
  129.             if [[ $am > $amount ]]; then
  130.                 let "count = $am - $amount"
  131.                 #echo count="$count"
  132.                 for (( i=0; i<$count; i++)); do
  133.                     for j in "$dirOutput""backup_"*"_folder"; do  
  134.                         #echo j="$j"
  135.                         rm -r $j
  136.                         break
  137.                     done
  138.                 done
  139.             fi    
  140.         elif ! [ "$5" == "0" ]; then
  141.             if [ "$lang" == "eng" ]; then            
  142.                 echo -e "\e[33;1mError in argument_5: This value in unexpected (expected 0 or 1), argument_5 is set to 0"
  143.             elif [ "$lang" == "rus" ]; then
  144.                 echo -e "\e[33;1mОшибка в аргумент_5: Непредвиденное значение аргумента (ожидалось 0 или 1), аргумент_5 установлен равным 0"
  145.             fi  
  146.         fi
  147.     fi
  148.     #=============================
  149.  
  150.     #=============================
  151.     cd $dirFolder
  152.     find . -name '*.'"$ext" | zip "$archiveName" -@ -q
  153.     #=============================
  154.  
  155.     #=============================
  156.     cd $dirOutput
  157.     mkdir $archiveName"_folder"
  158.     cd $dirFolder
  159.     cp $archiveName "$dirOutput""$archiveName""_folder"
  160.     echo $(cksum $archiveName) > "$archiveName""_cksum.txt"
  161.     cp "$archiveName""_cksum.txt" "$dirOutput""$archiveName""_folder"
  162.     rm $archiveName
  163.     rm "$archiveName""_cksum.txt"
  164.     #=============================
  165.    
  166.     #=============================
  167.     if [ "$lang" == "eng" ]; then
  168.         echo -e "\e[32;1mArchiving successed"
  169.     elif [ "$lang" == "rus" ]; then
  170.         echo -e "\e[32;1mАрхивация успешна"
  171.     fi
  172.     exit 0
  173.     #=============================
  174.  
  175. #====================================================================================================================
  176. # Checking the integrity of files / Проверка целостности архива
  177. #====================================================================================================================
  178. elif [[ "$task" == "-c" || "$task" == "--check" ]]; then
  179.     #=============================
  180.     if [ -n "$2" ]; then
  181.         if [ -f "$2" ]; then
  182.             fileArchiveName=$2
  183.         else
  184.             if [ "$lang" == "eng" ]; then
  185.                 echo -e "\e[31;1mError in argiment_2: No such directory" && exit 1
  186.             elif [ "$lang" == "rus" ]; then
  187.                 echo -e "\e[31;1mОшибка в аргумент_2: Данная директория не существует" && exit 1
  188.             fi
  189.         fi
  190.     else
  191.         if [ "$lang" == "eng" ]; then
  192.             echo -e "\e[31;1mError in argument_2: Argument is undefined" && exit 1
  193.         elif [ "$lang" == "rus" ]; then
  194.             echo -e "\e[31;1mОшибка в аргумент_2: Аргумент не найден" && exit 1
  195.         fi
  196.     fi
  197.     #=============================
  198.  
  199.     #=============================
  200.     folderArchiveName=$(dirname $fileArchiveName)
  201.     cd $folderArchiveName
  202.     fileCksumName="$fileArchiveName""_cksum.txt"
  203.  
  204.     cksumArchive=$(cksum $fileArchiveName)
  205.     IFS=' ' read -r -a array1 <<< "$cksumArchive"
  206.     cksumArchive=${array1[0]}
  207.  
  208.     cksumFile=$(head $fileCksumName)
  209.     IFS=' ' read -r -a array2 <<< "$cksumFile"
  210.     cksumFile=${array2[0]}
  211.     #=============================
  212.  
  213.     #=============================    
  214.     if [ "$cksumFile" == "$cksumArchive" ]; then
  215.         if [ "$lang" == "eng" ]; then
  216.             echo -e "\e[32;1mThe integrity of the archive is not violated"
  217.         elif [ "$lang" == "rus" ]; then
  218.             echo -e "\e[32;1mЦелостность архива не нарушена"
  219.         fi
  220.     else
  221.         if [ "$lang" == "eng" ]; then
  222.             echo -e "\e[31;1mThe integrity of the archive is violated" && exit 1
  223.         elif [ "$lang" == "rus" ]; then
  224.             echo -e "\e[31;1mЦелостность архива нарушена" && exit 1
  225.         fi
  226.     fi
  227.     #=============================
  228.  
  229. #====================================================================================================================
  230. # Setting the frequency of the script / Установка периодичности работы скрипта
  231. #====================================================================================================================
  232. elif [[ "$task" == "-p" || "$task" == "--period-set" ]]; then  
  233.     #=============================
  234.     #if [ -n "$2" ]; then
  235.     #    period=$2
  236.     #else
  237.     #    if [ "$lang" == "eng" ]; then
  238.     #        echo -e "\e[31;1mError in argument_2: Argument is undefined" && exit 1
  239.     #    elif [ "$lang" == "rus" ]; then
  240.     #        echo -e "\e[31;1mОшибка в аргумент_2: Аргумент не найден" && exit 1
  241.     #    fi
  242.     #fi
  243.     #=============================
  244.  
  245.     #=============================
  246.     #forHelp=0
  247.     #let "period += 0" 2>/dev/null || forHelp=1
  248.     #if [ "$forHelp" == "1" ]; then
  249.     #    if [ "$lang" == "eng" ]; then
  250.     #        echo -e "\e[31;1mError in argument_2: NaN" && exit 1
  251.     #    elif [ "$lang" == "rus" ]; then
  252.     #        echo -e "\e[31;1mОшибка в аргумент_2: NaN" && exit 1
  253.     #    fi
  254.     #fi
  255.     #=============================
  256.  
  257.     #=============================
  258.     if [ "$lang" == "eng" ]; then
  259.         echo -e "\e[32;1mEnter the command, that (crontab) will execute at the required frequency"
  260.     elif [ "$lang" == "rus" ]; then
  261.         echo -e "\e[32;1mВведите команду, которую (crontab) будет исполнять в с требуемой периодичностью"
  262.     fi
  263.     read strCommand
  264.     #=============================
  265.  
  266.     #=============================
  267.     if [ "$lang" == "eng" ]; then
  268.         echo -e "\e[32;1mEnter frequency of script startup (crontab syntax)"
  269.     elif [ "$lang" == "rus" ]; then
  270.         echo -e "\e[32;1mВведите периодичность запуска скрипта (синтаксис crontab)"
  271.     fi
  272.     read strFreq
  273.     #=============================
  274.  
  275.     #=============================
  276.     cd $dirFolderSc
  277.     echo -e "#!/bin/bash/\n""$strCommand"" 2>&1" > "$fileName""_crontab.sh"
  278.     chmod ugo+x "$fileName""_crontab.sh"
  279.     #/home/user/Desktop/hw/script.sh -a txt /home/user/Desktop/files/ /home/user/Desktop/b/ 1
  280.     #=============================
  281.  
  282.     #=============================
  283.     crontab -l | crontab -
  284.     echo "$strFreq"" ""$dirFolderSc""/""$fileName""_crontab.sh" | crontab -
  285.     #=============================
  286.  
  287. #====================================================================================================================
  288. # Changing script parameters / Изменение параметров скрипта
  289. #====================================================================================================================
  290. elif [[ "$task" == "-s" || "$task" == "--settings" ]]; then
  291.     #=============================
  292.     newLang="eng"
  293.     newAmount=1
  294.     #=============================
  295.  
  296.     #=============================
  297.     if [ -n "$2" ]; then
  298.         if [ "$2" == "eng" || "$2" == "rus" ]; then
  299.             newLang="$2"
  300.         else
  301.             if [ "$lang" == "eng" ]; then
  302.                 echo -e "\e[31;1mError in setting_2: This language is not supported" && exit 1
  303.             elif [ "$lang" == "rus" ]; then
  304.                 echo -e "\e[31;1mОшибка в параметр_2: Данный язык не поддерживается" && exit 1
  305.             fi
  306.         fi
  307.     else
  308.         if [ "$lang" == "eng" ]; then
  309.             echo -e "\e[31;1mError in setting_2: Setting in undefind" && exit 1
  310.         elif [ "$lang" == "rus" ]; then
  311.             echo -e "\e[31;1mОшибка в параметр_2: Параметр не найден" && exit 1
  312.         fi
  313.     fi
  314.     #=============================
  315.  
  316.     #=============================
  317.     if [ -n "$3" ]; then    
  318.         forHelp=$(expr "$3" + 0 2>/dev/null)
  319.         if [ -n "forHelp" ]; then
  320.             newAmount="$3"
  321.         else
  322.             if [ "$lang" == "eng" ]; then
  323.                 echo -e "\e[31;1mError in setting_3: Setting in invalid" && exit 1
  324.             elif [ "$lang" == "rus" ]; then
  325.                 echo -e "\e[31;1mОшибка в параметр_3: Параметр недействителен" && exit 1
  326.             fi
  327.         fi
  328.     else
  329.         if [ "$lang" == "eng" ]; then
  330.             echo -e "\e[31;1mError in setting_3: Setting in undefind" && exit 1
  331.         elif [ "$lang" == "rus" ]; then
  332.             echo -e "\e[31;1mОшибка в параметр_3: Параметр не найден" && exit 1
  333.         fi
  334.     fi
  335.     #=============================
  336.  
  337.     #=============================
  338.     echo -e "language: ""$newLang""\n""amountArchives: ""$newAmount" > "$fileSettingsName"
  339.     if [ "$newLang" == "eng" ]; then
  340.         echo -e "\e[32;1mSaving settings successed"
  341.     elif [ "$newLang" == "rus" ]; then
  342.         echo -e "\e[32;1mСохранение настроек успешно"
  343.     fi
  344.     #=============================
  345.  
  346. #====================================================================================================================
  347. # Help / Справка
  348. #====================================================================================================================
  349. elif [[ "$task" == "-h" || "$task" == "--help" ]]; then
  350.     if [ "$lang" == "eng" ]; then
  351.         echo ""
  352.         echo "DESCRIPTION"
  353.         echo "  This script allows you to archive the desired directory, check the integrity of the archive files, set the creation of backup copies of certain directories with some frequency."
  354.         echo ""
  355.         echo "ARGUMENTS"
  356.         echo "  -a  [arg_2] [arg_3] [arg_4] [arg_5] ...  --archive"
  357.         echo "      Creates archive of files with extension ([arg_2]=extension of files)"
  358.         echo "      at folder ([arg_3]=path to folder) and will store archive to the"
  359.         echo "      folder ([arg_4]=path to folder for archive) and if next argument"
  360.         echo "      ([arg_5]={0 or 1}, 1 - will use second parametr in file:"
  361.         echo "      'name_of_script_date'_folder, 0 - will not use.)"
  362.         echo "  -c  [arg_2] [arg_3] [arg_4]"
  363.  
  364.     elif [ "$lang" == "rus" ]; then
  365.         echo "ОПИСАНИЕ"
  366.         echo "  Данный скрипт позволяет заархивировать нужную директорию, проверить целостность файлов архива, установить создание резервных копий определённых директорий с некоторой периодичностью."
  367.         echo "АРГУМЕНТЫ"
  368.         echo ""
  369.     fi
  370.  
  371. #====================================================================================================================
  372. # Quit from script / Выход из скрипта
  373. #====================================================================================================================
  374. elif [[ "$task" == "-q" || "$task" == "--quit" ]]; then
  375.     exit 0;
  376. fi
  377.  
  378. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement